Next.js中使用getServerSideProps发起请求时cookies未发送到服务器是什么原因?
问题原因
getServerSideProps运行在Next.js的服务端环境,而非用户浏览器环境,axios的withCredentials: true配置仅对浏览器端请求生效,作用是让浏览器自动携带存储的Cookie,服务端运行axios时没有浏览器的Cookie存储池,不会自动挂载Cookie。- 用户的Cookie存储在本地浏览器中,只有用户发起页面请求时会把Cookie带到Next.js的服务端,你需要手动从
getServerSideProps的入参上下文里提取到用户的Cookie,再挂载到axios的请求头中传递给后端接口。
解决方案
修改getServerSideProps代码,手动传递Cookie:
export async function getServerSideProps(context) { // 从上下文的请求对象中提取用户携带的Cookie const userCookie = context.req.headers.cookie || '' const res = await axios.get("http://localhost:5000/api/auth", { headers: { Cookie: userCookie }, withCredentials: true }); const data = res.data; return { props: { data } } }
- 配置后你的后端JwtStrategy就能正常从
request.cookies里取到access字段,和浏览器端发请求的逻辑一致。 - 保留
withCredentials: true不影响服务端请求,同时如果这段请求逻辑复用到前端场景也能正常生效。
内容的提问来源于stack exchange,提问作者Овов Очоы
相关产品推荐
相关产品推荐

