Nodejs Frame Express Unable to get the session value solution

Source: Internet
Author: User
Tags redis install redis

We first look at the official sample code of the session in Express

First
$ NPM Install Redis
$ redis-server

var express = require ('.. /..');

var app = Express ();

App.use (Express.logger (' dev '));

Required by session () middleware
Pass the secret for signed cookies
(required by session ())
App.use (Express.cookieparser (' Keyboard Cat '));

Populates req.session
App.use (Express.session ());

App.get ('/', function (req, res) {
var body = ';
if (req.session.views) {
++req.session.views;
Res.send (body + ' <p>viewed <strong> ' + req.session.views + ' </strong> times.</p> ');
} else {
Req.session.views = 1;
Body + = ' <p>first time visiting? View this page in several browsers:) </p> ';
Res.send (body + ' <p>viewed <strong> ' + req.session.views + ' </strong> times.</p> ');
}
});

App.listen (3000);
Console.log (' Express app started on Port 3000 ');

Before you run, you need to know a few things:

Two lines of code for green grass are required, keyboard cat ' is the key used to encrypt cookies.

Session requires media storage storage, express.session () is stored in memory by default. There is also a commonly used method is stored in the database, Redis is a non-sql database, there are Nodejs Plug-ins can access him, Redis is commonly used. But given the weight, I didn't use it. Instead, it is stored in memory.

The session provides a regenerate method for emptying the entire session and then assigning the value again.

The problem I encountered was to create a new session in the login request using the Regenerate method of the session:

function login (request, response) {
...
Request.session.regenerate (function () {
Request.session.username = Userinfo.username;
Console.log ("set Session username =" + request.session.username);
Console.log (Request);
Response.Write (Json.stringify (Loginresult));
Response.End ();
} );
}

Then, in other requests after the login, determine if request.session.username exists, but not get it, request.session.username is undefined.

This question bothered me for 3 mornings, and I've been troubleshooting various possibilities:

I do not know if there is a problem in memory session, I did not run the express session of the official sample, later in the official sample code, I learned that this is not a problem. Before that, I tried using Redis to store the session, and later I thought that using the database was too heavy to accept the answer, so I gave up.

I wonder if query's Ajax request method did not pass the cookie in session to the background, through Google (thanks to google) I found the cookie property path, if set to/, then all requests will send this cookie, By grasping the bag also saw a cookie.

Because the client has sent, but the server did not receive, my logic has a request to jump, whether it is a jump after the session was reset? I began to observe each request session, by printing out each request session information, finally observed that each login, is an empty session will be generated before the session covered:

Sessionstore:
{sessions:
{' C+bfzyy2z23b8b3wa+fv6nco ': ' {' cookies ': {' originalmaxage ': null, ' expires ': null, ' HttpOnly ': true, ' path ': '/'} ',
Fk8djoqgwoyrq4jiffwu4hry: ' {"cookie": {"originalmaxage": null, "Expires": null, "HttpOnly": True, "path": "/"}, " Username ":" Lucy "} ',
' sjjychwsy+janarqvuw4jhl0 ': ' {cookie ': {' originalmaxage ': null, ' expires ': null, ' HttpOnly ': true, ' path ': '/'} ',

So it is certain that there is something wrong with the request, the session is covered. By searching, it is found that a claim is caused by the request Favicon function in the Express framework, which needs to be solved by adding app.use (Express.favicon ()); I tried, but I still couldn't.

I request.session.regenerate (function () {method has no bottom, so do not reconstruct the session, directly assign value, find the problem solved.

Later I will App.use (Express.favicon ()), after deletion, still no problem, this is more strange, because I have tried in the beginning do not use the request.session.regenerate (function () {, but not effective. But I think it's a cache problem, because the favicon on the browser has not changed since I used App.use (Express.favicon ());

But I added the request.session.regenerate (function () {method) to the sample code, and did not use App.use (Express.favicon ()); method, but there is no problem. I suspect that it is a multithreaded problem, and if you ask for more, there may be a problem.

This question, my final suggestion is: Use App.use (Express.favicon ()), methods, to assign values to the session, do not use Request.session.regenerate (function () { method to rebuild the session.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.