gpt4 book ai didi

javascript - 在 React 和 axios 中使用不同的 API url 进行开发和生产

转载 作者:行者123 更新时间:2023-11-29 20:48:59 25 4
gpt4 key购买 nike

我正在使用 React 前端和 Node.js 后端 (API) 构建网络应用程序。
在 React 前端,我这样调用 API 方法:

axios({
method: 'post',
url: 'http://servername:9999/reports.activities',
data: {
user_id: 1
}
}).then(res => {
this.setState(res.data);
});

有时我需要测试尚未发布到生产环境的 API 方法。
当我在本地测试后端时,我在 localhost:9999 上运行 nodemon api.js
每次我想使用本地运行的 API 测试前端时,我都必须在前端代码中将 http://servername:9999 更改为 http://localhost:9999 .
我认为这不是正确的做法。
为开发(在本地运行 npm start)和生产(npm build)使用不同 url 的最佳方式是什么?
我正在考虑使用 dotenv以此目的。这是正确的做法吗?
最佳做法是什么?

最佳答案

您可以创建 2 .env名为 .env.development 的文件和 .env.production .

//.env.development
REACT_APP_API_ENDPOINT=http://localhost:9999
//.env.production
REACT_APP_API_ENDPOINT=https://servername:9999

然后使用如下-

//api.js
const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT

axios({
method: 'post',
url: `${API_ENDPOINT}/reports.activities`,
data: {
user_id: 1
}
}).then(res => {
this.setState(res.data);
});

它的工作方式是:当你运行 npm start , React 将使用 .env.development文件和你什么时候做npm run build , React 将使用 .env.production文件。

这是 documentation 的相关部分.

关于javascript - 在 React 和 axios 中使用不同的 API url 进行开发和生产,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52896204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com