【问题标题】:Is there a elegant way to manage API url in my project code有没有一种优雅的方式来管理我的项目代码中的 API url
【发布时间】:2022-01-25 04:36:39
【问题描述】:

我猜这是开发中很常见的问题

我正在使用 nextjs 项目。在其中我对我的本地 api 服务器进行了几次 api 调用。

后来,我将我的 api 服务器迁移到 AWS,在那里我获得了下一个 js 项目的新 URL。

例如,

const res = await axios.post("http://localhost:3050/login/", newUser)
.catch(function (error) {
    if (error.response.data.errorMessage) {
        throw new Error(error.response.data.errorMessage || 'Something went wrong!');
    }
})

const searchResults = await fetch(`http://localhost:3050/search/find`).then((res) => res.json());

所以,我将在下一个 js 中更改我的代码并硬编码新的 URL。

但是,问题是我仍处于开发阶段,即使我已经将我的 api 服务器上传到云上。

有时候,我还是想切换回使用我的本地 api 服务器。

因此,在测试中,我总是必须更改下一个 js 中每个 API 调用的所有 URL。 (我有一堆api调用)

请问是否有针对此目的的最佳做法?

【问题讨论】:

  • 使用.env文件管理它们
  • .env 在下一个 js 中可能吗?有什么例子吗,谢谢?

标签: reactjs api dev-to-production


【解决方案1】:

简单!在 Next.js 应用程序的根目录中创建一个 .env 文件。在此文件中,声明您需要的所有环境变量,如下所示:

API_URL = "http://localhost:3050"

然后,在您的代码中,您可以使用 process.env.VARIABLE_NAME 来引用这些变量

示例:

const res = await axios.post(`${process.env.API_URL}/login`, newUser)
.catch(function (error) {
    if (error.response.data.errorMessage) {
        throw new Error(error.response.data.errorMessage || 'Something went wrong!');
    }
})

const searchResults = await fetch(`${process.env.API_URL}/search/find`).then((res) => res.json());

【讨论】:

  • 所以我会有下面的例子,在 .env API_URL = "localhost:3050" API_URL = "production:3050" API_URL = "UAT:3050" 我必须注释掉所有其他非当我不在那些环境中时相关吗?这被认为是最快的方式?
  • 我觉得这个是最快的方式,只需要改一处
猜你喜欢
  • 2010-10-24
  • 1970-01-01
  • 1970-01-01
  • 2011-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多