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

知道吗?


当前回答

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

我换了每个

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

})

to

Axios.post(`/createOrder`, {

})

它成功了!

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

其他回答

我的情况是,我在启动时运行数据库脚本,花费了很长时间。我在部署完成后手动运行npm start来解决这个问题。

在开发应用程序时,我们需要以以下方式定义PORT:

const port = process.env.PORT || 4000; // PORT must be in caps

在将应用程序部署到服务器时,添加以下方法:

app.listen(port, () => {
 console.info("Server started listening.");
});

我们可以在本地运行主机名时将主机名作为第二个参数传递。但是在将其部署到服务器时,应该删除主机名参数。

app.listen(port, hostName, () => {
  console.info(`Server listening at http://${hostName}:${port}`);
});

我也有同样的问题,但是是express和apollo-server。解决方法:

唯一需要特别考虑的是允许 Heroku选择服务器部署到的端口。否则, 可能会出现错误,比如请求超时。 为了配置apollo-server在运行时使用Heroku定义的端口, 可以使用端口调用安装文件中的listen函数 由PORT环境变量定义:

> server.listen({ port: process.env.PORT || 4000 }).then(({ url }) => { 
> console.log(`Server ready at ${url}`); });

在使用yeoman的angular-fullstack生成项目时,我也有同样的问题,删除IP参数对我有用。

我替换了这段代码

server.listen(config.port, config.ip, function () {
  console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});

server.listen(config.port, function () {
  console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});

在我的例子中,我使用Babel plugin-transform-inline-environment-variables插件。显然,Heroku在进行部署时没有设置PORT env变量,因此process.env.PORT将被undefined取代,并且您的代码将回退到Heroku不知道的开发端口。