我有我的第一个node.js应用程序(本地运行良好)-但我无法通过heroku部署它(第一次w/ heroku也是如此)。代码如下。SO不让我写这么多代码,所以我只想说在我的网络中本地运行代码也没有问题。

 var http = require('http');
 var fs = require('fs');
 var path = require('path');

 http.createServer(function (request, response) {

    console.log('request starting for ');
    console.log(request);

    var filePath = '.' + request.url;
    if (filePath == './')
        filePath = './index.html';

    console.log(filePath);
    var extname = path.extname(filePath);
    var contentType = 'text/html';
    switch (extname) {
        case '.js':
            contentType = 'text/javascript';
            break;
        case '.css':
            contentType = 'text/css';
            break;
    }

    path.exists(filePath, function(exists) {

        if (exists) {
            fs.readFile(filePath, function(error, content) {
                if (error) {
                    response.writeHead(500);
                    response.end();
                }
                else {
                    response.writeHead(200, { 'Content-Type': contentType });
                    response.end(content, 'utf-8');
                }
            });
        }
        else {
            response.writeHead(404);
            response.end();
        }
    });

 }).listen(5000);

 console.log('Server running at http://127.0.0.1:5000/');

知道吗?


当前回答

在你的包裹里。json文件,在脚本中,确保你的启动脚本包含-p $PORT。

包的示例。json(在这种情况下,为NextJS应用程序):

{
  "private": true,
  "scripts": {
    "dev": "next dev -p 3001",
    "build": "next build",
    "start": "next start -p $PORT" // make sure to have -p $PORT in here
  },
  "dependencies": {
    "typescript": "^4.3.2"
  },
  "devDependencies": {
    "@next/eslint-plugin-next": "^11.1.2",
    "@types/mongoose": "^5.11.97"
    "typescript": "^4.3.2"
  }
  "license": "MIT"
}

其他回答

我会建议你很好地阅读日志,以便轻松排除故障。 如果你引用一个PORT作为环境变量(env),请确保它是PORT而不是PORT,因为heroku会在你部署应用程序时自动分配一个PORT号。process.env.PORT不是process.env.PORT

改变这一行

app.listen(port);

to

app.listen(process.env.PORT, '0.0.0.0');

会有用的

如果你得到这个错误,上面没有工作,错误不是来自R10本身。错误是由R14(内存配额超过)引起的,这是因为部分代码使用multer (multi . diskstorage()方法)或其他一些库来存储使用某种形式的本地存储的图像或其他文件。R14错误导致的延迟将导致R10(引导超时)错误。

解决方案:

在你的包裹里。Json文件,把你的开始改为“start”:“node——max-old-space-size=4096 server/index.js”。这增加了存储大小。

also

设置这个heroku变量 heroku canfig:set NODE_ENV=dev

我也有同样的问题,但我的环境变量设置得很好,npm和node的版本在package.json中指定。我发现这是因为,在我的情况下,Heroku需要在package.json中指定“start”:

  "scripts": {
    "start": "node index.js"
  }

把这个加到我的包里之后。我的节点应用程序成功部署在Heroku。

当Heroku在服务器上绑定端口或主机名失败时发生错误。监听(port, [host], [backlog], [callback])。

Heroku需要的是.listen(process.env. port)或.listen(process.env. port)。港口,“0.0.0.0”)

所以更一般地,为了支持其他环境,使用这个:

var server_port = process.env.YOUR_PORT || process.env.PORT || 80;
var server_host = process.env.YOUR_HOST || '0.0.0.0';
server.listen(server_port, server_host, function() {
    console.log('Listening on port %d', server_port);
});