简体   繁体   中英

Get cookie on front-end

I use on back-end nodejs(nestjs). From the server i send the cookies after login:

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

And this is my cors setting app.enableCors({credentials: true }); ;
As front-end i use reactjs. After login the server sent the cookies here: 在此处输入图像描述

But i need to get the cookies here: 在此处输入图像描述
Why i don't get the cookies in the place where i showed and how to get them there to save them even o reloading the page?

The reason the cookie is not persisted in the frontend is that you are probably not setting the withCredentials on your frontend request. An example with axios would be:

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

An example with fetch is:

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

Note: For security reasons you must have explicitly specified the origin on your backend CORS configuration otherwise you will get the following error:

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.

To do that with nest.js/express you can pass:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM