StevenZ
StevenZ

Reputation: 141

Nodejs: session is undefined after generating

I have a problem in using express 4 and express-session in my node/html project.

  1. The login.html makes an ajax call to the node program.

  2. If it succeeds, node generates a session remembering the user name in the attribute req.session.username and return a file name csmain.html to login.html. login.html then redirects the browser to csmain.html.

  3. The csmain.html then makes an ajax call in its load() immediately, but the problem is at this time the session seems to not be ready. The req.session.user is undefined in node. That means the session has not been used by the browser in the ajax call in load().

Any ideas how this can be solved?

code in node's login part to generate a session

request.session.regenerate(function(err) {
});
if (request.session.views ) {
  // empty
} else {
  request.session.views = 1;
  request.session.username = username;
}

html redirect --javascript part in the login html. The 1st character in the xmlHttp.responseText is the status of login, the remaining text is the http link

if (status === BDX_ERR_SQL_WRONG_PASSWORD) {
    document.getElementById("feedbackMsg").innerHTML = 'login error';
}else if (status === '0') {
    window.location = '../' + xmlHttp.responseText.substring(1, len);
}

Upvotes: 0

Views: 235

Answers (1)

jfriend00
jfriend00

Reputation: 707746

Since you are using a database as a session store, then it is likely that the regenerate() call is asynchronous. That means that regenerate() is not done until the callback is called so you would need to do it this way:

request.session.regenerate(function(err) {
    // should do error checking here

    if (request.session.views ) {
        // empty
    } else {
        request.session.views = 1;
        request.session.username = username;
    }

    // continue with the rest of your code flow here inside the callback

});

Express session doc here: https://github.com/expressjs/session#sessionregenerate

Upvotes: 1

Related Questions