There are several moving parts, so it's difficult to know what to debug here.

I have a web application on one localhost port, and a simple helper on another localhost running an express NodeJS application with a couple of endpoints.

The basic issue I'm seeing is that my cookie session on the express application is empty for subsequent calls, and I don't even see it being sent back in the first response.

The setup

The client makes basic GET ajax calls (jQuery at the moment) to the express application.

I have set http allowance for session cookies:

app.use(cookieSession({
  name: 'session',
  keys: ['abcdefg'],
  maxAge: 24 * 60 * 60 * 1000, // 24 hours,
  secure: false
}))

I have set cross-origin requests on the express application:

app.use((req, res, next) => {
    const corsWhitelist = [
        'http://localhost:8000',
        'http://localhost:8777'
    ];
    if (corsWhitelist.indexOf(req.headers.origin) !== -1) {
        res.header('Access-Control-Allow-Origin', req.headers.origin);
        res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    }

    next();
});

And the requests are completed seemingly without issue, as the response bodies are what I expect.

The meat of the request handler is:

app.get('/initialize', (req, res) => {
    console.log(req.session);

    //if we have a session with verified status 
    if (req.session.hasOwnProperty("userId") && req.session.userId){
        res.send({result: 'OK', message: 'good - 1'});
        return;
    }

    const id = uuid.v4();
    req.session.userId = id;
    res.send({result: 'OK', message: 'good - 2'});
    return;
});

I always always get the second response 'good - 2' from the ajax call. The log always shows the session as {}

It's probably worth noting that Chrome devtools shows "Provisional headers are shown" for the request headers, and set-cookie is not shown in the response headers. The AJAX is a simple GET to an endpoint with one parameter passed in.

Update

Just now occurred to me to try without using the AJAX call. Hitting the URL directly gets the cookie and keeps the session as expected. That will probably change the dynamic of the issue.

1 Answers

0
Randy Hall On

The fix was to use jsonp request/response to get cookies to pass around the ajax call. Nothing to do with express really.

https://samueleresca.net/2015/07/json-and-jsonp-requests-using-expressjs/