【问题标题】:How do you access the URL in a NextJS app?如何访问 NextJS 应用程序中的 URL?
【发布时间】:2019-08-21 10:06:26
【问题描述】:

在我的代码中,我进行 API 调用,但我希望能够同时使用 dev 和 prod,所以通常我会执行以下操作:

let res = await fetch(`${process.env.SERVER_URL}/api/category/initialCategoryMeta?category=${category}`

如何在 NextJS 中执行类似操作,以便在运行应用程序时设置 SERVER_URL?

【问题讨论】:

  • 这里缺少很多信息,请大家发帖时说清楚!

标签: javascript node.js next.js


【解决方案1】:

构建时间配置

module.exports = {
  env: {
    customKey: 'value',
  },
}

这将允许您在代码中使用 process.env.customKey。例如:

function Index() {
    return <h1>The value of customKey is: {process.env.customKey}</h1>
}

export default Index

运行时配置

您可以设置next.config.js文件

// next.config.js
module.exports = {
  serverRuntimeConfig: {
    // Will only be available on the server side
    mySecret: 'secret',
    secondSecret: process.env.SECOND_SECRET, // Pass through env variables
  },
  publicRuntimeConfig: {
    // Will be available on both server and client
    staticFolder: '/static',
  },
}

然后访问 next/config

中的值
// pages/index.js
import getConfig from 'next/config'
// Only holds serverRuntimeConfig and publicRuntimeConfig from next.config.js nothing else.
const { serverRuntimeConfig, publicRuntimeConfig } = getConfig()

Next Runtime config

【讨论】:

  • 对不起,这并没有解决开发人员和产品的问题,这解决了非常不同的客户端和服务器。
  • @DanFein 您可以在配置文件build time configuration 中设置构建的相同方式@
猜你喜欢
  • 2013-10-26
  • 2018-01-27
  • 1970-01-01
  • 1970-01-01
  • 2020-06-16
  • 1970-01-01
  • 1970-01-01
  • 2019-12-09
  • 2021-09-15
相关资源
最近更新 更多