【问题标题】:What is the best location to store the API Root Url in React JS?在 React JS 中存储 API 根 URL 的最佳位置是什么?
【发布时间】:2021-02-28 13:13:39
【问题描述】:

我正在一个项目中使用 mern stack。

目前我正在像这样向其余 api 发出请求。

const { data } = await axios.get('http://localhost:5000/api/testimonials/');

API 可在http://localhost:5000/ 获得

但是当我部署这个应用程序时,url 会改变。

使用当前方法,我已将http://localhost:5000/ 替换为实时网址。

我不想这样做,而是将根 url 存储在一个变量中。

在 React JS 中存储 API 根的最佳位置是什么?

所以我可以在我提出的每个请求中使用它,当我必须更新 url 时,我只需要更新那个变量。

【问题讨论】:

    标签: node.js reactjs axios


    【解决方案1】:

    你可以做两件事,

    1. 通过为每个环境创建 .env 文件将它们存储在 env 变量中

      CRA - .env

      不要忘记在你的名字前加上 REACT_APP_ ,否则它不会起作用

    2. 在 package.json 中使用代理。(这是在文档中使用 api 的首选方式)

      它避免了文档中提到的cors 错误

      CRA - proxy

    【讨论】:

    • 我想我会使用代理。
    【解决方案2】:

    您必须使用 .env 文件来保存根 url。 .env 应该位于根目录。

    .env 文件内容:

    rooturl=http://yourproductiondomain.com
    

    你可以在你的代码上使用进程:

    const rooturl = process.env.rooturl || 'http://localhost:5000'; // for lcoalhost.. **.env** file does not work on localhost.
    const { data } = await axios.get(rooturl + '/api/testimonials/');
    

    【讨论】:

    • dotenv 在服务器中使用。不是我相信的客户。
    猜你喜欢
    • 2016-09-29
    • 2015-12-05
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-05
    • 2011-08-01
    相关资源
    最近更新 更多