when you enter the site, cookies are set and everything goes fine, but when you reload the page, the set cookies are deleted
response from login(back):
export const sendAccessTokenAndRefreshToken = (response:ServerResponse, accesstoken:string, refreshtoken:string) => {
response.writeHead(200, {
'Content-Type': 'text/json; application/json',
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Methods": "GET,PUT,POST,DELETE,PATCH,OPTIONS",
"Access-Control-Allow-Origin": "http://localhost:3000",
"Access-Control-Allow-Headers": "Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Authorization",
'Set-Cookie': [`refreshtoken=${refreshtoken}; Secure; HttpOnly; SameSite=None; Path=/; Max-Age=99999999;`]
});
response.end(JSON.stringify({accesstoken}));
}
respons options (cors):
response.writeHead(200, {
'Content-Type': 'text/json; application/json',
"Access-Control-Allow-Credentials": "true",
"Access-Control-Allow-Origin": "http://localhost:3000",
"Access-Control-Expose-Headers": "Authorization",
"Access-Control-Allow-Headers": "Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Authorization",
});
response.end(JSON.stringify({message: 'Cors Work!'}));
when login is done:
after site reload:
in this picture you can see when sending a post request, cookies are displayed, but after a reboot it disappears
front login.js:
const body = {
login: login_input.value,
password: password_input.value
}
fetch('http://127.0.0.1:3000/login', {
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json'
},
credentials: 'include',
body: JSON.stringify(body)
})
.then((response) => response.json())
.then((json) => {
localStorage.setItem('token', json.accesstoken);
How to solve this problem? I tried to use the cors browser extension but even that did not help
how to solve this problem without resorting to extraneous frameworks?
I suspect is the use of the ' and ` quotes in the code below:
"Access-Control-Allow-Headers": "Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Authorization",
'Set-Cookie': [refreshtoken=${refreshtoken}; Secure; HttpOnly; SameSite=None; Path=/; Max-Age=99999999;]
Remove the '` and also remove the [] you are not supposed to have that either.
Something like:
"Set-Cookie": "refreshtoken=${refreshtoken}; Secure; HttpOnly; SameSite=None; Path=/; Max-Age=99999999;"
then it is a different question if it is a good idea to store the refresh tokens in a cookie, but that's a different discussion.