gpt4 book ai didi

apache2 - 从 Nuxt 请求中获取当前域名

转载 作者:行者123 更新时间:2023-12-04 13:41:06 26 4
gpt4 key购买 nike

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

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

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

export default function({ store, req }) {
if (process.server) store.commit('hostname', req.headers.host)
}

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

最佳答案

如果你使用 Vuex,你可以使用 nuxtServerInit访问请求 header 的操作。
在我的示例中,我将域存储在 Vuex 中,因此可以在应用程序的任何位置访问它,因为该中间件在所有其他中间件之前触发。
store/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,
};
中间件/domain.js
export default function ({ route, store, redirect }) {
console.log('hey look at that', store.getters['domain']);
}
nuxt.config.js
export default {
...

router: {
middleware: 'domain'
},
}

关于apache2 - 从 Nuxt 请求中获取当前域名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56854595/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com