Nodejs uses express to obtain get and post values and the session verification method, nodejsexpress
This article describes how nodejs uses express to obtain get and post values and verify the session. We will share this with you for your reference. The details are as follows:
Get and post values
The get value is put into an object.
req.query
The post value is put in
req.body
Obtain the object content in the same way. For example, if a value of id is input, you can obtain the req. body. id from nodejs.
Express session Verification
Step 1 install the cookie and session modules and introduce
var session = require('express-session');var cookieParser = require('cookie-parser');
Part 2: express Application cookie and session
App. use (cookieParser (); app. use (session ({resave: true, // don't save session if unmodified saveUninitialized: false, // don't create session until something stored secret: 'admin ', // key name: 'testapp', // The name here is the cookie name. The default cookie name is connect. sid cookie: {maxAge: 80000} // set maxAge to 80000 ms, that is, the session and the corresponding cookie expire after 80 s }));
Step 3: intercept and process requests
App. use (function (req, res, next) {if (! Req. session. user) {if (req. url = "/login") {next (); // if the requested address is a logon address, the next request is sent.} else {res. redirect ('/login'); // jump to the logon page} else if (req. session. user) {next (); // if you have logged on, you can enter }});
If you do not log on to the access page, the route is automatically directed to the/login page. The last step is to process the route
App. get ('/login', function (req, res) {res. render ("login") ;}); app. post ('/login', function (req, res) {if (req. body) {// The value var user = {'username': req. body. username // get the username and assign a value. You can make your own judgment here}; req. session. user = user; // assign a value to the session to automatically jump to the page res. redirect ('/admin');} else {res. redirect ('/login') ;}}); app. get ('/logout', function (req, res) {// do the logout page req. session. user = null; res. redirect ('/login ');});
I hope this article will help you design nodejs programs.