javascript - node.js 项目在本地机器上工作,在 Heroku 上部署时出现问题

标签 javascript node.js heroku web-deployment web-hosting

我有一个我一直在做的 node.js + Express 项目,当我在我的机器上运行它时它一直在工作。我已经为我的 Express API 设置了端口 4200,使用

var port = 4200;

在 app.js 中

我在 React 中使用 axios 访问 API:

axios.get('https://localhost:4200/posts ... etc

当我在我的机器上运行它时一切正常,但是当我用 Heroku 部署它时,我得到这个错误:

GET https://localhost:4200/posts net::ERR_CONNECTION_REFUSED

Error: Network Error at createError (createError.js:16) at XMLHttpRequest.handleError (xhr.js:87)

我该如何解决这个问题?

最佳答案

有两点我想强调:

1) 引自 https://devcenter.heroku.com/articles/deploying-nodejs#specifying-a-start-script

The command in a web process type must bind to the port number specified in the PORT environment variable. If it does not, the dyno will not start.

那么你应该做的是

var port = process.env.PORT || 4200;

现在,当在本地系统上工作时,将使用端口 4200,当部署到由环境变量分配的 heroku 端口时,将被使用。

2) 根据您的问题,您说您正在使用 axios.get('https://localhost:4200/posts ... etc。部署应用程序时,它应该如何使用 localhost?

将 localhost 更改为您在 Heroku 上创建应用程序时获得的任何域。

关于javascript - node.js 项目在本地机器上工作,在 Heroku 上部署时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47257143/

相关文章:

python - 在 Python 中更改包安装顺序

ruby-on-rails-3 - Heroku 预编译 Assets 没有结果

maven - jBCrypt 依赖项不起作用

javascript - 根据另一个数组对一个数组进行排序

javascript - 找到父文档后如何查询mongoDB子文档

javascript - jQuery 没有得到应用

node.js - 我的 sequelize-auto 命令执行抛出错误 "Please install tedious package manually"

javascript - Phaser JS 如何停止从 textButton.events.onInputDown 事件到 game.input.onDown 事件的事件传播(触发)?

node.js - NodeJS中的 `require`是否可以认为是在require的词法位置加载文件?

node.js - 是否可以覆盖bunyan的日志功能?