Cookie and Session in Node

Posted by slipperyfish on Mon, 26 Aug 2019 17:40:04 +0200

1,Cookie

HTTP is a stateless protocol. Example: Open the home page of a domain name, and then open other pages of the domain name, the server can not identify visitors. That is, the same browser visits the same website, each visit has nothing to do with it.

Cookie's principle is that after the client browser first accesses the server, the server returns a section of json data to identify, and then when the client browser accesses the same domain again, it carries this cookie information with it every time.

Characteristic

  • Cookies are not encrypted and users can see them freely.
  • Users can delete cookie s or disable them. If the expiration time is not set, the browser will fail by default after closing the browser.
  • Cookies can be tampered with
  • Cookies can be used for attacks
  • Cook storage is small. (less than 4k)

Cookie is non-cross-domain. According to the Cookie specification, browsers accessing Google will only carry Google's Cookie, not Baidu's Cookie. Google can only operate Google's Cookie, not Baidu's Cookie.

Cookies are used in Node.js:

 1 const cookieParser = require('cookie-parser');     //Modular  cookie-parser
 2 const app = express();
 3 app.use(cookieParser());               //middleware
 4 app.get('/',(req,res)=>{
 5     res.send('Root routing');
 6 })
 7 app.get('/login',(req,res)=>{
 8     //Get Client cookies
 9     console.log(req.cookies);
10 
11     //Server Download cookie
12     res.cookie('heaven','666',{
13         maxAge:900000                //Effective time, milliseconds
14     });
15     res.send('ok');
16 })
17 
18 app.listen(3000);

2,Session

The server needs to record the user's status. It depends on cookie to track session. When the first session is created, the server will tell the client in HTTP protocol that it needs to record a session ID in the cookie. The server can identify the client every time the client requests to carry the session ID.

Characteristic

  • Session is not a natural technology, but a reliance on cookies. When a browser disables cookies, the login effect disappears; or when the user clears the cookie, the login disappears.
  • What's the difference between session and cookie? Session sends out scrambled code, and the server caches something by itself; next time the browser comes up with scrambled code, compare it with the cache and see who it is.
session is used in Node.js
/*
     session  The data is stored in the server, but the index is stored in the browser, which identifies the corresponding session according to cookieid.
     npm i express-session -S  Using session module
 */
const express = require('express');
const session = require('express-session');     // analysis session Modules    express-session
const app = express();

//start-up session Middleware, formulas
app.use(session({           //Require client to set an encrypted cookie
    secret:'heaven',        //Any character will do. Here you go. cookie encryption
    cookie:{maxAge:300000},
    resave:true,
    saveUninitialized:true,
}))
//Middleware is executed sequentially, so intercept it in front
app.get('/favicon.ico',(req,res)=>{
    return;
})

app.get('/',(req,res)=>{
    res.send('Your footprint is'+req.session.lvyou);
})
app.get('/:city',(req,res)=>{
    let city = req.params.city;
    // console.log(req.session);
    let cityArr = req.session.lvyou || [];
    cityArr.push(city);
    req.session.lvyou = cityArr;
    res.send("You went today."+city);
})

app.listen(3000);
/*
       Extract session from memory into mongo database
       npm i connect-mongo -S     Module for storing session in mongo database
*/
const express = require("express"),
    app = express(),
    session = require("express-session"),
    Mongosession = require("connect-mongo")(session),
    mongoose = require("mongoose");
//Connect to the database
mongoose.connect("mongodb://localhost/bounty",{useNewUrlParser: true})
//session formula
app.use(session({
    secret:"doukeyi",           //Secret key,encryption
    rolling:true,               //Each interaction (operation page, a Label, ajax)Reset the time
    cookie:{maxAge:1000*60*60}, //cookie Validity period 1 hour
    resave:false,               //Whether the data is saved again every time a request is made
    saveUninitialized:false,    //Whether to set the initial value by default
    store:new Mongosession({
        url:"mongodb://localhost/bounty"        //session Store in the database and automatically clear the database when it expires
    })
}))
/*
    Clear session
*/
router.get("/logout",function (req,res) {
    req.session.destroy();
    res.redirect("/login");
})

3. Distinction

  • Cookies are plain codes; session s are random codes;
  • cookie exists in client browser and session exists in server.
  • cookie memory is small, session memory is large;

Topics: Javascript Session Database Google Mongoose