Home > Web Front-end > JS Tutorial > Express Session implements login verification function (code attached)

Express Session implements login verification function (code attached)

php中世界最好的语言
Release: 2018-04-18 11:08:36
Original
1916 people have browsed it

This time I will bring you Express Session to implement the login verification function (with code). What are the precautions for Express Session to implement the login verification function. The following is a practical case, let's take a look.

Many people are exploring the use of Express and Session to implement login verification. This article will briefly introduce how to use Express and Session to implement login verification. What is the specific implementation code? Let’s find out together.

1. Write

in front When we log in to a website, we close the website without logging out. After a while, when we open the website again, we will still be logged in. This is because when we log in to a website, the server will save our login status until we log out or the saved login status expires. So how does the server store our login status? The answer is Session, through which the service can record the status of each client connection. I won’t say much about the principle of Session here. This article mainly introduces how to use Session to implement User loginauthentication in the Express framework.

2. Environment configuration

In the Node environment, there is no library integrating Express and Session, so you need to install it. First, enter and create a project directory, and then use the following commands to install four modules in the project root directory.

1) Express

This module allows us to quickly build a web development framework.

2) body-parser

This module is the middleware of the Express module, which facilitates us to parse the body data sent by the browser.

3) express-session

This module is also the Express module middleware, which facilitates us to handle client sessions.

4) ejs

This module is a rendering engine. It is convenient for us to bind the background variablesdata to the front page.

Installation is as follows:

npm install express --save
npm install body-parser --save
npm install express-session --save
npm install ejs --save
Copy after login

3. Login and verification

Session can mark the client's status on the server. Using this, we can implement client-side login verification. The process of session login verification is roughly as follows: if the client requests the homepage while not logged in, the server will redirect the request to the login page; after the client logs in, the server needs to record and save the client's login status and give a Activity period, so that the next time the server requests the home page, it can determine the client's login status. If the login status is valid, it will directly return to the page the client needs, otherwise it will redirect to the login page.

Regarding the Session expiration time, if the Session expiration time is not set, the server will delete Sessions that have not interacted with the server for a long time based on the default validity period in its own configuration.

The example code is posted below. The interface is relatively simple, and the server background code comments are clearly written, so I will not explain it again.

The project's directory structure is as follows:

Login page (login.html) code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style type="text/css">
  </style>
</head>
<body>
  <form action="/login" method="POST">
    用户名: <input type="text" name="username"/> <br>
    密码: <input type="password" name="pwd"/>
    <input type="submit" value="Submit"/>
  </form>
</body>
</html>
Copy after login

The home page (home.html) code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
  <p>用户名:<span><%= username %> </span> <a href="/logout" rel="external nofollow" >退出登录</a></p>
</body>
</html>
Copy after login

The server (app.js) code is as follows:

/**
 * Created by tjm on 9/7/2017.
 */
var express = require('express');
var app = express();
var session = require('express-session');
var bodyparser = require('body-parser');
// 下面三行设置渲染的引擎模板
app.set('views', dirname); //设置模板的目录
app.set('view engine', 'html'); // 设置解析模板文件类型:这里为html文件
app.engine('html', require('ejs').express); // 使用ejs引擎解析html文件中ejs语法
app.use(bodyparser.json()); // 使用bodyparder中间件,
app.use(bodyparser.urlencoded({ extended: true }));
// 使用 session 中间件
app.use(session({
  secret : 'secret', // 对session id 相关的cookie 进行签名
  resave : true,
  saveUninitialized: false, // 是否保存未初始化的会话
  cookie : {
    maxAge : 1000 * 60 * 3, // 设置 session 的有效时间,单位毫秒
  },
}));
// 获取登录页面
app.get('/login', function(req, res){
  res.sendFile(dirname + '/login.html')
});
// 用户登录
app.post('/login', function(req, res){
  if(req.body.username == 'admin' && req.body.pwd == 'admin123'){
    req.session.userName = req.body.username; // 登录成功,设置 session
    res.redirect('/');
  }
  else{
    res.json({ret_code : 1, ret_msg : '账号或密码错误'});// 若登录失败,重定向到登录页面
  }
});
// 获取主页
app.get('/', function (req, res) {
  if(req.session.userName){ //判断session 状态,如果有效,则返回主页,否则转到登录页面
    res.render('home',{username : req.session.userName});
  }else{
    res.redirect('login');
  }
})
// 退出
app.get('/logout', function (req, res) {
  req.session.userName = null; // 删除session
  res.redirect('login');
});
app.listen(8000,function () {
  console.log('http://127.0.0.1:8000')
})
Copy after login

At this point, session login verification is completed. In the above example, the session is saved in the service memory. Of course, it can also be saved in a file or database. You only need to configure the session middleware.

app.use(session({
  secret: 'secretkey',
  store: new MongoStore({
    db: 'sessiondb'
  })
}));
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

node.js implements read-write synchronization function

How to compare two strings Same data

The above is the detailed content of Express Session implements login verification function (code attached). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template