在 React 和 axios 中使用不同的 API url 进行开发和生产 [英] Using different API url for development and production with React and axios

查看:64
本文介绍了在 React 和 axios 中使用不同的 API url 进行开发和生产的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm building web app with React frontend and Node.js backend (API).
In React frontend I call API methods like this:

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.
我认为这不是正确的方法.
使用不同 url 进行开发(在本地运行 npm start 时)和生产(npm build)的最佳方法是什么?
为此,我正在考虑使用 dotenv.这是正确的方法吗?
最佳做法是什么?

Sometimes I need to test API methods that is not released to production yet.
When I test backend locally, i run nodemon api.js on localhost:9999.
Every time I want to test frontend with local-running API, I have to change http://servername:9999 to http://localhost:9999 in my frontend code.
I think this is not the right approach.
What is the best way to use different url for development (when run npm start locally) and production (npm build)?
I was thinking of using dotenv for this purpose. Is this the right approach?
What is the best practice?

推荐答案

如果您使用的是 create-react-app,则您已经安装了 dotenv.

If you are using create-react-app you have already dotenv installed.

https://create-react-app.dev/docs/adding-custom-environment-variables/#adding-development-environment-variables-in-env

所以你可以这样做:

const API_ENDPOINT = process.env.REACT_APP_API_ENDPOINT || 'http://production';

...
url: `${API_ENDPOINT}/reports.activities`

这篇关于在 React 和 axios 中使用不同的 API url 进行开发和生产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆