1

我正在尝试baseUrl根据 nuxt.config.js 中的请求标头动态设置 nuxt/i18n 的属性

nuxt.config.js

i18n: {
    baseUrl: ({ req }) => {
      return "https://" + req.headers.host;
    }
},

这行不通。有没有办法访问请求标头?

努克斯特:v2.15.7

i18n/nuxt:v7.0.1

4

2 回答 2

1

最后,找到了另一个解决方案。Nuxt.config.js 在服务器端和客户端使用不同的上下文进行处理。在服务器端,我获取请求host标头并通过nuxtState. 更多信息在这里:https ://nuxtjs.org/docs/2.x/internals-glossary/context#beforenuxtrender

nuxt.config.js

i18n: {
    baseUrl: (context) => {
      // get the hostname from http request headers on the server side and save it to nuxtState
      if (process.server) {
        const { req, beforeNuxtRender } = context;
        beforeNuxtRender(({ nuxtState }) => {
          nuxtState.host = req.headers.host;
        });
      }
      return (
        "https://" +
        (process.server ? context.req.headers.host : context.nuxtState.host)
      );
    },
...
},
于 2021-08-17T16:38:53.013 回答
0

您可以serverMiddleware在您的nuxt.config.js文件中使用

serverMiddleware: ['~/server-middleware/logger']

~/server-middleware/logger.js

export default function (req, res, next) {
  console.log('current host', req.headers.host)
  next()
}

也许设置一个cookie或类似的,然后在你nuxt.config.js的其他模块中使用它。


否则,它也在 Nuxt 上下文中使用:https
://nuxtjs.org/docs/2.x/concepts/context-helpers 所以,要么asyncData,要么。pluginsmiddlewarenuxtServerInit

于 2021-08-16T17:31:09.843 回答