使用不同的 API url 用于 React 和 axios 的开发和生产
Using different API url for development and production with React and axios
我正在使用 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 尚未发布到生产环境的方法。
当我在本地测试后端时,我 运行 nodemon api.js
on localhost:9999
.
每次我想使用 local-运行ning API 测试前端时,我都必须在前端代码中将 http://servername:9999
更改为 http://localhost:9999
。
我认为这不是正确的做法。
将不同的 url 用于开发(当 运行 npm start
本地)和生产(npm build
)的最佳方法是什么?
为此,我正在考虑使用 dotenv。这是正确的方法吗?
最佳做法是什么?
如果您使用的是 create-react-app,那么您已经安装了 dotenv。
所以你可以这样:
const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT || 'http://production';
...
url: `${API_ENDPOINT}/reports.activities`
您可以创建 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 的相关部分。
我正在使用 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 尚未发布到生产环境的方法。
当我在本地测试后端时,我 运行 nodemon api.js
on localhost:9999
.
每次我想使用 local-运行ning API 测试前端时,我都必须在前端代码中将 http://servername:9999
更改为 http://localhost:9999
。
我认为这不是正确的做法。
将不同的 url 用于开发(当 运行 npm start
本地)和生产(npm build
)的最佳方法是什么?
为此,我正在考虑使用 dotenv。这是正确的方法吗?
最佳做法是什么?
如果您使用的是 create-react-app,那么您已经安装了 dotenv。
所以你可以这样:
const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT || 'http://production';
...
url: `${API_ENDPOINT}/reports.activities`
您可以创建 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 的相关部分。