在前端获取cookie

我在后端 nodejs(nestjs) 上使用。我在登录后从服务器发送 cookie:

res.cookie('token', 'token', {
  httpOnly: true
});

回答

cookie 没有保留在前端的原因是您可能没有withCredentials在前端请求中设置 。axios 的一个例子是:

axios.post('http://localhost:3001', {}, { withCredentials: true })

fetch 的一个例子是:

fetch(url, {
    method,
    headers: { 
        'Content-Type': 'application/json' 
    },
    credentials: 'include'  
}

注意:出于安全原因,您必须在后端 CORS 配置中明确指定来源,否则您将收到以下错误:

Access to XMLHttpRequest at 'http://localhost:3001/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
Access to XMLHttpRequest at 'http://localhost:3001/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

要使用 nest.js/express 做到这一点,您可以通过:


以上是在前端获取cookie的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>