在前端获取 cookie

IT技术 node.js reactjs nestjs
2021-05-06 14:59:31

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

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

这是我的 cors 设置app.enableCors({credentials: true });
作为前端,我使用 reactjs。登录后,服务器将 cookie 发送到这里: 在此处输入图片说明

但是我需要在这里获取 cookie: 为什么我没有在我展示的地方获取 cookie,以及如何将它们放到那里以保存它们甚至重新加载页面?在此处输入图片说明

1个回答

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.

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

app.enableCors({
   credentials: true,
   origin: ['http://localhost:3002', 'your-production-domain'] 
});