[英]Connecting react front end and express backend
The dev build works fine, with my react app on port 3000 and server on port 8080. The front end is able to make requests to the backend and get the response.开发构建工作正常,我的反应应用程序在端口 3000 上,服务器在端口 8080 上。前端能够向后端发出请求并获得响应。 But when deploying the production build, the application starts on port 5000 and the static files are rendered.But the front end can't access localhost:8080/api/:id because that port isn't 'on'.
但是在部署生产版本时,应用程序在端口 5000 上启动,并呈现 static 文件。但是前端无法访问 localhost:8080/api/:id 因为该端口未“打开”。 Any help will be appreciated.
任何帮助将不胜感激。
You can use dotenv to define custom config variables and cross-env package to define an environment for your react application.您可以使用dotenv定义自定义配置变量,并使用cross-env package 为您的反应应用程序定义环境。 First install these packages.
首先安装这些软件包。
yarn add dotenv && yarn add cross-env --dev
or或者
npm i dotenv && npm i cross-env --dev
You need create two separate.env config files, name them as .env.development
and .env.production
.您需要创建两个单独的 .env 配置文件,将它们命名为
.env.development
和.env.production
。 Your env file may contain something like this:您的 env 文件可能包含如下内容:
.env.development .env.development
API_URL="localhost:8080"
.env.production .env.production
API_URL="localhost:5000"
Now on your react's main.js
file(or what you have named), just import the dotenv
package as follows:现在在您的 react 的
main.js
文件(或您命名的文件)上,只需导入dotenv
package,如下所示:
// other imports here
require('dotenv').config({
path: process.env.NODE_ENV === 'production' ? '/path/to/.env.production' : '/path/to/.env.development'
})
Now, on your package.json
, change the start and build script as such:现在,在您的
package.json
上,更改启动和构建脚本,如下所示:
{
...
"scripts": {
"start": "cross-env NODE_ENV=development react-scripts start",
"build": "cross-env NODE_ENV=production react-scripts build",
...
}
...
}
Finally, wherever you have been using the API URL:最后,无论您在哪里使用 API URL:
Example例子
axios.post(`${process.env.API_URL}/your/path`) // or any other way to join URL and path
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
Hope it helps to solve your issue.希望它有助于解决您的问题。
From all your routes
remove localhost:8080
and make direct request to /api/
because everything is running under one PORT which is 5000
.从所有
routes
中删除localhost:8080
并直接请求/api/
因为一切都在一个 PORT 下运行,即5000
。 You might need to re-build your front-end with changes made您可能需要通过所做的更改重新构建前端
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.