我遇到了 next.js 的问题
当我从 async static getInitialProps
发出请求时,我无法获取我的 cookie。我得到 undefined
然而,当我在 componentWillMount
中制作它时,没有问题。不幸的是,为时已晚,因为我需要在调用组件之前获取 cookie 信息。所以我需要在 getInitialProps
这是我已经尝试过但没有成功的方法:
static async getInitialProps () {
const res = await axios.get('http://mybackend/getCookie');
return {data : res.data}
}
//res.data = undefined
有什么建议吗?
最佳答案
这可能是客户端 vs 服务器的事情 - componentWillMount()
只在客户端运行,所以那里的请求总是包含客户端的 cookie。但是,getInitialProps
可能会在服务器上运行,在这种情况下,您必须手动设置 cookie。
您可以通过测试 options.req 的存在来判断它是在客户端还是在服务器上运行:
static getInitialProps({ req }) {
if (req) {
console.log('on server, need to copy cookies from req')
} else {
console.log('on client, cookies are automatic')
}
return {};
}
并且,当在服务器上运行时,您可以通过检查req.headers.cookie
来读取客户端的cookie。因此,对于 axios,它可能看起来像这样:
static async getInitialProps({req}) {
const res = await axios({
url: 'http://mybackend/getCookie',
// manually copy cookie on server,
// let browser handle it automatically on client
headers: req ? {cookie: req.headers.cookie} : undefined,
});
return {data : res.data}
}
关于node.js - 如何使用 next.js 的 getInitialProps 方法获取 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44755043/