Express is one of the frameworks of Node.js. Session is a method of managing client status on the server side. The server is the network system running on the computer. The client is the computer or smartphone that accesses the server. By using sessions, you can easily manage the number of times the server is accessed from the same client.
How to use express session?
First we need to install
Installation command
npm install --save express-session
In npm install, use npm to install the express-session module.
Use the -save option to save installation information.
Basic syntax of session
实例名称.use(session({ 设置内容: '值', }))
Declares that the object specified by the instance name uses the session in use.
Specify session processing in session.
The setting item in the second line: 'value', specifies the specific processing to be completed.
Specify the setting item and the value set for the setting item respectively.
Specific usage of express session
Basic source code
var app = express() app.set('trust proxy', 1) app.use(session({ secret: 'keyboard cat', resave: false, saveUninitialized: true, cookie: { secure: true } }))
Analysis:
In the first line, var app=express() uses the express function to create an instance named app.
In the second line, app.set('trust proxy', 1) sets the application as the first trust proxy.
A proxy is a server.
By using a proxy, you can enable unrestricted Internet access even in environments restricted by Internet firewalls.
The third line, app.use(session({ declares the use of session.
Secret in line 4: 'keyboard cat', we set to use the block chain as the key to encrypt the cookie.
Cookie is like a management variable stored on the client side.
A variable is like a box containing a value.
In line 5, resave: false, specifies that each session Whether to create a session when checking. By setting it to false, specify not to create a session each time.
In line 6, saveUninialized: true, specifies whether to save uninitialized sessions. Specify true to save.
In line 7, cookie: {secure: true} sets the validity time of the cookie (in milliseconds). If not specified or null, it is the browser's default behavior (usually when closing the browser Delete cookies).
})) in the eighth line represents the completion of the processing of the third line.
This is the entire content of this article. For more related exciting content, you can pay attention to other column tutorials on the php Chinese website! ! !
The above is the detailed content of How to use express session in node.js. For more information, please follow other related articles on the PHP Chinese website!