我有一个在http://localhost:4050 上运行的 NodeJS 后端,并且我已经配置了我的 React 应用程序来进行 API 调用。为了在 heroku 上部署,我必须将后端的 PORT 变量更改为process.env.PORT. 结果当我把react应用程序的build文件夹放在后端的server文件夹中时,react应用程序在我部署到heroku时仍在搜索localhost:4050,自然无法调用,因为heroku在任意不同的端口上运行应用程序。但显然将非常相同的http://localhost:4050是"proxy":"http://localhost:4050"在package.json文件的工作。我真的很好奇这样做是如何让它发挥作用的。
create-react-app 的 package.json 中的“代理”字段如何工作?
IT技术
node.js
reactjs
express
heroku
2021-05-04 14:00:50
1个回答
proxy字段 inpackage.json用于代理从前端域到后端的所有请求。例如,您有:
- 后端(REST API):本地主机:5000/api/user/:id
- 前端(React.JS 应用程序):本地主机:3000/用户
如果您调用axios.get('/api/user/123'),浏览器会将此请求发送到localhost:3000/api/user/123,然后react开发服务器会将其发送到localhost:5000/api/user/123
请注意,这仅适用于开发环境。如果你想部署你的 React.JS,有一个更好的方法:https ://blog.heroku.com/deploying-react-with-zero-configuration