Home >Web Front-end >Front-end Q&A >What is the usage of session in node?
In node, session is used for the interaction between the visitor and the website. It is used to track the identity of the client user and is called session information; the session will be passed to the web when the accessing browser requests the http address. on the server and match the access information; the session data is saved on the server, and permanent data cannot be saved.
The operating environment of this tutorial: Windows 10 system, nodejs 12.19. Version 0, Dell G3 computer.
session is called session information. It is located on the web server and is mainly responsible for the interaction between the visitor and the website. When the accessing browser requests the http address, It will be passed to the web server and matched with the access information. When the website is closed, it means that the session has ended and the website cannot access the information, so it cannot save permanent data. We cannot access and disable the website
cookie and session are both ways to track the identity of the client user. They provide great convenience for multi-page webs, allowing the server to clearly identify different users, but they also have certain differences.
Difference: Cookie data is saved on the client side, and session data is saved on the server side.
session
Install module
cnpm install express-session
Introduce
var express = require('express'); var session = require('express-session'); var app = express(); app.use(session({secret: 'keyboard cat', resave: false, saveUninitialized: true, cookie: {maxAge: 60000}}));
Use
router.get('/set', function (req, res, next) { //设置session req.session.username = 'zhangsan'; res.send('ok'); }); router.get('/get', function (req, res, next) { //获取session console.log(req.session); console.log(req.session.username); res.send('session的值:‘+req.session); });
Note: session only exists in During the current session, the connection is disconnected and the session disappears
Summary: If we need to log in to a site frequently, it is best to use cookies to save information, otherwise it will be particularly troublesome to log in every time. If security is required High-end sites and the ability to control data need to use sessions for better results. Of course, we can also combine the two to make the website run according to our ideas.
Recommended learning: "nodejs video tutorial》
The above is the detailed content of What is the usage of session in node?. For more information, please follow other related articles on the PHP Chinese website!