简体   繁体   English

node.js项目在本地计算机上运行,​​在Heroku上部署时出现问题

[英]node.js Project Works on Local Machine, Issues when Deployed on Heroku

I have a node.js + Express project that I've been working on, and it's been working when I run it on my machine. 我有一个一直在工作的node.js + Express项目,当我在自己的机器上运行它时它一直在工作。 I've set port 4200 for my Express API, with 我已经为Express API设置了端口4200,

var port = 4200;

in app.js 在app.js中

I access the API using axios in React: 我在React中使用axios访问API:

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

This all works when I run it on my machine, but when I deploy this with Heroku, I get this error: 当我在机器上运行它时,所有这些都可以工作,但是当我用Heroku部署它时,出现此错误:

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

Error: Network Error at createError (createError.js:16) at XMLHttpRequest.handleError (xhr.js:87) 错误:XMLHttpRequest.handleError(xhr.js:87)的createError(createError.js:16)出现网络错误

How do I fix this? 我该如何解决?

There are two thing I would like to highlight: 我想强调两件事:

1) Quoting from https://devcenter.heroku.com/articles/deploying-nodejs#specifying-a-start-script 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. Web进程类型中的命令必须绑定到PORT环境变量中指定的端口号。 If it does not, the dyno will not start. 如果没有,则测功机将不会启动。

So what you should do is 所以你应该做的是

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

Now when working on local system port 4200 will be used and when deployed on heroku port assigned by environment variable will be used. 现在,在本地系统上工作时,将使用端口4200,而在heroku端口上部署时,将使用环境变量分配的端口。

2) From your question you say you are using axios.get('https://localhost:4200/posts ... etc . When app is deployed how is it supposed to use localhost ? 2)从您的问题中,您说您正在使用axios.get('https://localhost:4200/posts ... etc 。)在部署应用程序时,应如何使用localhost

Change localhost to whatever the domain you get when creating app on Heroku. 将localhost更改为在Heroku上创建应用程序时获得的任何域。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM