【问题标题】:How can I get the request hostname in nuxt.config.js/i18n?如何在 nuxt.config.js/i18n 中获取请求主机名?
【发布时间】:2021-10-18 16:54:44
【问题描述】:

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

nuxt.config.js

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

这不起作用。有什么方法可以访问请求标头吗?

Nuxt:v2.15.7

i18n/nuxt:v7.0.1

【问题讨论】:

  • 请求主机名是什么意思?您是否在寻找客户端版本又名location.origin?您不想为此传递一个 ENV 变量吗?
  • 抱歉,如果我不清楚,我正在寻找服务器端版本,即 context.req.headers.hostname。我知道我可以在 .env 文件中指定它并在配置中使用,但我想为多个域提供服务,并且必须从请求中获取域名。

标签: nuxt.js nuxt-i18n


【解决方案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)
      );
    },
...
},

【讨论】:

    【解决方案2】:

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

    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
    所以,asyncDatapluginsmiddlewarenuxtServerInit

    【讨论】:

    • 好的,谢谢,那么如何将主机名变量从中间件传递给 nuxt.config.js?
    • And maybe set a cookie or alike, then use it in your nuxt.config.js for the other modules.@user2779340
    猜你喜欢
    • 2013-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-22
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    相关资源
    最近更新 更多