[英]API URL changes after npm build React
My React App communicates with a backend service using an API endpoint as follows:我的 React 应用程序使用 API 端点与后端服务通信,如下所示:
const API_URL = process.env.REACT_APP_API_URL;
const response = await fetch(`${API_URL}/data`);
The environment variable REACT_APP_API_URL
is saved in a .env
file which looks like this:环境变量
REACT_APP_API_URL
保存在.env
文件中,如下所示:
REACT_APP_API_URL="http://1.2.3.4:8000"
When I serve the app using npm start
everything works fine and the developer console shows that the call was made to the right URL:当我使用
npm start
为应用程序提供服务时,一切正常,开发人员控制台显示调用正确的 URL:
Request URL: http://1.2.3.4:8000/data
I received the data as expected as well.我也按预期收到了数据。 But when I run
npm run build
and then serve the app with serve -s build/ -l 3000
the app fails to fetch because the request goes to the following URL:但是当我运行
npm run build
然后使用serve -s build/ -l 3000
为应用程序提供服务时,应用程序无法获取,因为请求转到以下 URL:
Request URL: http://localhost:3000/1.2.3.4:8000/
What am I missing for this to happen?我错过了什么?
So the problem was not with my React App or the environment variables but with the way I was serving the app所以问题不在于我的 React 应用程序或环境变量,而在于我为应用程序提供服务的方式
The listening argument -l
in the serve
command is the culprit. serve
命令中的监听参数-l
是罪魁祸首。 It should be -p
for the port to host on它应该是
-p
用于托管的端口
So the right command is所以正确的命令是
serve -s build/ -p 3000
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.