从 Nuxt 中的请求获取当前域名

Phi*_* S. 8 apache2 hostname server-side-rendering nuxt.js

如何从服务器端的请求中获取当前域名?

我的基于 Nuxt 的网站可以从不同的域访问。我想从用户访问网站的地方获取域名。我怎样才能做到这一点?

我尝试为此目的编写一个中间件,但它总是显示 localhost:3000

export default function({ store, req }) {
  if (process.server) store.commit('hostname', req.headers.host)
}
Run Code Online (Sandbox Code Playgroud)

知道如何解决这个问题吗?

agm*_*984 6

如果您使用的是 Vuex,则可以使用该nuxtServerInit操作来访问请求标头。

在我的示例中,我将域存储在 Vuex 中,以便可以在应用程序中的任何位置访问它,因为该中间件在所有其他中间件之前触发。

商店/index.js

export const state = () => ({
    domain: '',
});

export const mutations = {
    setDomain(state, domain) {
        state.domain = domain;
    },
};

export const actions = {
    nuxtServerInit(store, context) {
        store.commit('setDomain', context.req.headers.host);
    },
};

export const getters = {
    domain: (state) => state.domain,
};
Run Code Online (Sandbox Code Playgroud)

中间件/domain.js

export default function ({ route, store, redirect }) {
    console.log('hey look at that', store.getters['domain']);
}
Run Code Online (Sandbox Code Playgroud)

nuxt.config.js

export default {
    ...

    router: {
        middleware: 'domain'
    },
}
Run Code Online (Sandbox Code Playgroud)


Vil*_*los 1

我可以通过以下方式获取在服务器上声明该功能的域名:

export default function (req, res, next) {
    console.log(req.headers.host)
}
Run Code Online (Sandbox Code Playgroud)

如果您需要将数据提交到存储,将数据保存在环境中并在客户端恢复它可能是一个解决方案。