在Next.js中进行服务器端渲染时访问cookie可能比你想象的要难。下面是我的解决方法。
我遇到了这个问题。我的应用程序依赖cookie进行验证,而使用Next.js时,显然我的cookie没有在第一页初始化时被设置。
我有这样的代码,它负责使用Axios打一个GET端点。
Bookings.getInitialProps = async ctx => {
const response = await axios.get('http://localhost:3000/api/bookings/list')
return {
bookings: response.data
}
}
我在服务器端端点上有Passport.js,但它未能在SSR页面上对用户进行认证,因为它没有找到任何cookie。
我不得不把我的代码改成这样,把cookie加入到headers 。
Bookings.getInitialProps = async ctx => {
const response = await axios({
method: 'get',
url: 'http://localhost:3000/api/bookings/list',
headers: ctx.req ? { cookie: ctx.req.headers.cookie } : undefined
})
return {
bookings: response.data
}
}
让cookie在后端可用的关键是添加。
headers: ctx.req ? { cookie: ctx.req.headers.cookie } : undefined
到Axios的配置中。