我有我的第一个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/');

知道吗?


当前回答

如果你得到这个错误,上面没有工作,错误不是来自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

其他回答

我的问题是当部署到heroku时,我得到了一个错误:

Web进程在启动后60秒内未能绑定到$PORT

当运行heroku日志时——终端中的tail。但是当我在本地运行服务器时,应用程序将按预期运行。

我在index.js文件(服务器文件)中有这个

const PORT = process.env.port || 4000

app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`)
})

但是应该有这个

const PORT = process.env.PORT || 4000

app.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`)
})

使用process.env。PORT,而不是process.env。port,因为port和port显然不一样。

这是格兰桑特的功劳。

Heroku动态地为你的应用程序分配端口,所以你不能将端口设置为一个固定的数字。Heroku将端口添加到env,所以你可以从那里拉它。让我们来听听这个:

.listen(process.env.PORT || 5000)

这样,当你在本地测试时,它仍然会监听端口5000,但它也可以在Heroku上工作。重要提示- PORT字必须大写。

你可以在这里查看Node.js上的Heroku文档。

编辑package.json:

...
"engines": {
"node": "5.0.0",
"npm": "4.6.1"
},
...

和Server.js:

...
var port = process.env.PORT || 3000;
app.listen(port, "0.0.0.0", function() {
console.log("Listening on Port 3000");
});
...

我浪费了一整天的时间思考后台有问题。在经历了这里所有的解决方案和彻底的日志检查后,意识到这是前端反应App.js有问题。

我换了每个

Axios.post(`${process.env.REACT_APP_BASE_URL}/createOrder`, {

})

to

Axios.post(`/createOrder`, {

})

它成功了!

显然,react文件与heroku部署无关!

我意识到在请求端点中不需要端口号,因此端点是herokuapp.com,而不是herokuapp.com:5000。

listen()调用可以没有host和callback:

server.listen(5000);