3. How to use session in node

Although cookies are very convenient, there is a big disadvantage in using cookies. All the data in cookies can be modified at the client, and the data is very easy to be forged, so some important data cannot be stored in cookies, and if there are too many data fields in cookies, the transmission efficiency will be affected. In order to solve these problems, a session is generated, and the data in the session is retained on the server side.


Session operates through a session_id #. session_id , is usually stored in the cookie of the client. For example, in express, the default is , connect Sid # this field. When the request arrives, the server checks the session saved in the cookie_ Pass this session ID_ ID is associated with the session data on the server side to save and modify the data.


This means that when you browse a web page, the server randomly generates a 1024 bit long string, which is then stored in your cookie Sid field. When you visit the next time, the cookie will carry this string, and then the browser will know that you have visited so and so last time, and then take the data recorded on you from the server's storage. Because the string is generated randomly and has enough digits, I don't worry that someone can forge it. The probability of successful forgery is lower than that of being suddenly broken in and killed by a neighbor's dog while sitting at home programming.

Sessions can be stored in

1) memory

2) cookie itself

3) redis or memcached

4) in the database

Online, caching schemes are common. If you save the database, the query efficiency is too low compared with the first three, so it is not recommended;

Express session is used to operate session in express( https://github.com/expressjs/session ) the main method of this module is session(options), in which options contain optional parameters, mainly including:

  • Name: set the field name of the session saved in the cookie. The default is connect sid .
  • Store: the storage method of session. It is stored in memory by default. redis, mongodb, etc. can also be used. The express ecosystem is supported by corresponding modules.
  • Secret: calculate the hash value through the set secret string and put it in the cookie to make the generated signedCookie tamper proof.
  • Cookie: set the relevant options for storing the cookie of session id. the default is
    • (default: { path: '/', httpOnly: true, secure: false, maxAge: null })
  • genid: generate a new session_id, the npm package "uid2" is used by default.
  • rolling: reset a cookie for each request. The default is false.
  • resave: save the session value even if the session has not been modified. The default value is true.
1. Installation package
You need to install the package of express session and cookie parser
npm install express-session

npm install cookie-parser


2. Introduction package

var express=require("express")
var app=express()

//Reference session
var session=require("express-session");
var cookieParser=require("cookie-parser")


3. Open the cookie and configure the contents of the session

// In express, session information is stored in memory
// Configure session
    secret:"dsafsafsf", //The content of the set signature secret key can be filled in arbitrarily
    cookie:{ maxAge:80*1000 }, //Set the expiration time of cookies, for example: session and corresponding cookies expire after 80s
    resave:true, //Forced save. If the session has not been modified, it should be saved again
    saveUninitialized:false //If the session has not been set for so long, otherwise it will not be set


4. Set the contents of the session

    //Store data in session
    req.session.name='jack'; //loginok: can be any content, and can be true or false
    res.send("Added successfully")


5. Read the contents of the session

//Read session
    //View session
    res.send("query was successful")


6. Delete session
    res.redirect("http://www.baidu.com "); / / after deletion, go to Baidu page
    res.send("Deleted successfully")


7. Listening port

app.listen(8000,function () {   console.log('') })

The session in node stores the value in memory and cannot be viewed directly in the browser;

Therefore, write the session into the cookie, and then view the corresponding file name in the browser when the session is stored

Note: id in the session is a keyword and cannot be stored in it. It conflicts with the default field in the session


8. Page prompt

app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
     res.locals.error = 'Username or password incorrect ';


9. Route verification

Through session


10. crypto encryption

npm install crypto

Route introduction

var crypto = require('crypto'); / / encryption
 var password1 = req.body.password1;
var md5 = crypto.createHash('md5');

var userPwd = md5.update(password1).digest('hex');



Tags: node.js

Posted by niwa3836 on Sat, 07 May 2022 14:58:16 +0300