search
HomeWeb Front-endJS TutorialExpress Session implements login verification function (code attached)

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

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:

nbsp;html>


  <meta>
  <title>Title</title>
  <style>
  </style>


  
    用户名:  
    密码:         

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

nbsp;html>


  <meta>
  <title>Title</title>


  <p>用户名:<span> </span> <a>退出登录</a></p>

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')
})

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'
  })
}));

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
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
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

See all articles

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 agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools