I have a login
route where I want to set a cookie after I verify the login credentials. The client and the server are on different ports.
const app = express();
app.use(
cors({
credentials: true,
origin: true,
})
);
app.use(cookieParser());
app.use('/login', (req, res) => {
res.cookie('secureCookie', JSON.stringify({ id: 1 }), {
secure: false,
httpOnly: true,
});
return res.json({ success: true });
});
app.use('/check', (req, res) => {
console.log(req.cookies);
return res.json({ id: 1 });
});
The issue is that I don't see the cookie in the devtools (applications tab) after the login request returns. Also, when trying to fetch the check
endpoint using credentials: 'include'
it doesn't send the cookie.
What I'm doing wrong?
Here are the requests:
fetch('http://localhost:4000/login');
fetch('http://localhost:4000/check', {
credentials: 'include',
});
CodePudding user response:
According to Using Fetch article on mdn
Unless fetch() is called with the credentials option set to include, fetch():
- won't send cookies in cross-origin requests
- won't set any cookies sent back in cross-origin responses
credentials: include
must be set for requests to make them save cookies
CodePudding user response:
just delete return
res.json({ success: true });