【问题标题】:Using different API url for development and production with React and axios通过 React 和 axios 使用不同的 API url 进行开发和生产
【发布时间】:2018-10-19 16:10:09
【问题描述】:

我正在使用 React 前端和 Node.js 后端 (API) 构建 Web 应用程序。
在 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
我认为这不是正确的方法。
使用不同 url 进行开发(在本地运行 npm start 时)和生产(npm build)的最佳方式是什么?
我正在考虑为此目的使用dotenv。这是正确的方法吗?
最佳做法是什么?

【问题讨论】:

    标签: javascript reactjs axios create-react-app


    【解决方案1】:

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

    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`
    

    【讨论】:

      【解决方案2】:

      您可以创建 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的相关部分。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-06-28
        • 2017-07-27
        • 1970-01-01
        • 1970-01-01
        • 2011-11-14
        • 2021-07-29
        • 1970-01-01
        相关资源
        最近更新 更多