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

Express Session implements login verification function (code attached)

Apr 18, 2018 am 11:08 AM
express session verify

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to verify signature in PDF How to verify signature in PDF Feb 18, 2024 pm 05:33 PM

We usually receive PDF files from the government or other agencies, some with digital signatures. After verifying the signature, we see the SignatureValid message and a green check mark. If the signature is not verified, the validity is unknown. Verifying signatures is important, let’s see how to do it in PDF. How to Verify Signatures in PDF Verifying signatures in PDF format makes it more trustworthy and the document more likely to be accepted. You can verify signatures in PDF documents in the following ways. Open the PDF in Adobe Reader Right-click the signature and select Show Signature Properties Click the Show Signer Certificate button Add the signature to the Trusted Certificates list from the Trust tab Click Verify Signature to complete the verification Let

Detailed method to unblock using WeChat friend-assisted verification Detailed method to unblock using WeChat friend-assisted verification Mar 25, 2024 pm 01:26 PM

1. After opening WeChat, click the search icon, enter WeChat team, and click the service below to enter. 2. After entering, click the self-service tool option in the lower left corner. 3. After clicking, in the options above, click the option of unblocking/appealing for auxiliary verification.

How to solve session failure How to solve session failure Oct 18, 2023 pm 05:19 PM

Session failure is usually caused by the session lifetime expiration or server shutdown. The solutions: 1. Extend the lifetime of the session; 2. Use persistent storage; 3. Use cookies; 4. Update the session asynchronously; 5. Use session management middleware.

Solution to PHP Session cross-domain problem Solution to PHP Session cross-domain problem Oct 12, 2023 pm 03:00 PM

Solution to the cross-domain problem of PHPSession In the development of front-end and back-end separation, cross-domain requests have become the norm. When dealing with cross-domain issues, we usually involve the use and management of sessions. However, due to browser origin policy restrictions, sessions cannot be shared by default across domains. In order to solve this problem, we need to use some techniques and methods to achieve cross-domain sharing of sessions. 1. The most common use of cookies to share sessions across domains

New features in PHP 8: Added verification and signing New features in PHP 8: Added verification and signing Mar 27, 2024 am 08:21 AM

PHP8 is the latest version of PHP, bringing more convenience and functionality to programmers. This version has a special focus on security and performance, and one of the noteworthy new features is the addition of verification and signing capabilities. In this article, we'll take a closer look at these new features and their uses. Verification and signing are very important security concepts in computer science. They are often used to ensure that the data transmitted is complete and authentic. Verification and signatures become even more important when dealing with online transactions and sensitive information because if someone is able to tamper with the data, it could potentially

How to validate IFSC code using regular expressions? How to validate IFSC code using regular expressions? Aug 26, 2023 pm 10:17 PM

Indian Financial System Code is the abbreviation. Indian bank branches participating in the electronic funds transfer system are identified by a special 11-character code. The Reserve Bank of India uses this code in internet transactions to transfer funds between banks. IFSC code is divided into two parts. Banks are identified by the first four characters, while branches are identified by the last six characters. NEFT (National Electronic Funds Transfer), RTGS (Real Time Gross Settlement) and IMPS (Immediate Payment Service) are some of the electronic transactions that require IFSC codes. Method Some common ways to validate IFSC codes using regular expressions are: Check if the length is correct. Check the first four characters. Checkthefifthcharacter.Che

How to validate route parameters in Laravel? How to validate route parameters in Laravel? Sep 01, 2023 pm 02:41 PM

In Laravel, routes are defined in the paths/ folder. Routes are defined in the web.php file. This file is created after laravel installation is complete. Laravel routes accept URIs and closure functions as follows - useIlluminate\Support\Facades\Route;Route::get('/student',function(){return'HelloStudent';}); in web/routes.php Defined routes are assigned to web middleware groups, and they have session state and CSRF protection. You can also call the controller in the route like below

What are the differences between JavaScript and PHP cookies? What are the differences between JavaScript and PHP cookies? Sep 02, 2023 pm 12:29 PM

JavaScriptCookies Using JavaScript cookies is the most effective way to remember and track preferences, purchases, commissions and other information. Information needed for a better visitor experience or website statistics. PHPCookieCookies are text files that are stored on client computers and retained for tracking purposes. PHP transparently supports HTTP cookies. How do JavaScript cookies work? Your server sends some data to your visitor's browser in the form of a cookie. Browsers can accept cookies. If present, it will be stored on the visitor's hard drive as a plain text record. Now, when a visitor reaches another page on the site

See all articles