Trying to work out a CORS request using the fetch method:
fetch('https://foobar.com/auth', {
method: 'GET',
mode: 'cors',
credentials: 'include',
})
The server-side code in express for implementing CORS protection on one route is as follows:
app.get('/auth', cors({
origin: [
'http://localhost:8080',
'http://127.0.0.1:8080'
],
credentials: true,
preflightContinue: true
}), (req, res) => {
const { jwt } = req.cookies;
console.log('JWT is: ', jwt);
res.json({ jwt });
});
Unfortunately, even though the request includes a cookie, the response always comes back empty.
The response headers show:
access-control-allow-credentials: true
access-control-allow-origin: http://127.0.0.1:8080
Directly hitting the /auth
route on the server does return JSON with the JWT token stored as a cookie that passes between client and server.
{"jwt":"[token string here]"}
In addition, the response headers also include:
set-cookie: connect.sid=s%3As-DAIzZjWT4C3xxxxxuAUgE; Path=/; HttpOnly; Secure
Questions arise about whether the set-cookie for the JWT should be visible in the response, indicating if it's being handled correctly by the server and sent back in the response to the CORS request. The process involves setting proper headers on the server side and specifying correct origins while enabling credentials to receive cookies.