Table of Contents
登录页面
in services/UserService.js" >##2️⃣ Define the API interface in services/UserService.js
In the previous sectionCookie-Session" >3️⃣ Configure sessionIn the previous sectionCookie-Session
Set when logging in successfullysession" >4️⃣ Permission verificationSet when logging in successfullysession
5️⃣ 退出登录" >5️⃣ 退出登录
6️⃣ 链接数据库" >6️⃣ 链接数据库
Home Web Front-end JS Tutorial Node practice: using Cookie&Session for login verification

Node practice: using Cookie&Session for login verification

Dec 01, 2022 pm 08:16 PM
nodejs​ node

Node practice: using Cookie&Session for login verification

##Original address: https://ailjx.blog.csdn.net/article/details/127909213

Author: Undersea BBQ Restaurant ai

In the previous sections we have created and optimized the project structure of the simple user management system, and also explained the working principle of

Cookie-Session login verification. Next we We will continue to supplement the functions of this system. In this section, we will actually use Cookie-Session to implement the login verification function of this system. [Related tutorial recommendations: nodejs video tutorial]

What? You still don’t understand

session, cookie! Go check out the previous article: Detailed explanation of how Cookie-Session login authentication works

##1️⃣ Define page routingCreate a new

login.ejs

in the vies directory: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; &lt;meta http-equiv=&quot;X-UA-Compatible&quot; content=&quot;IE=edge&quot;&gt; &lt;meta name=&quot;viewport&quot; content=&quot;width=device-width, initial-scale=1.0&quot;&gt; &lt;title&gt;Document&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1 id=&quot;登录页面&quot;&gt;登录页面&lt;/h1&gt; &lt;div&gt;用户名:&lt;input type=&quot;text&quot; id=&quot;username&quot;&gt;&lt;/div&gt; &lt;div&gt;密码:&lt;input type=&quot;password&quot; id=&quot;password&quot;&gt;&lt;/div&gt; &lt;div&gt;&lt;button id=&quot;login&quot;&gt;登录&lt;/button&gt;&lt;/div&gt; &lt;script&gt; const uname = document.getElementById(&quot;username&quot;); const pwd = document.getElementById(&quot;password&quot;); const login = document.getElementById(&quot;login&quot;); login.onclick = () =&gt; { fetch(&amp;#39;/api/login&amp;#39;, { method: &amp;#39;POST&amp;#39;, body: JSON.stringify({ username: uname.value, password: pwd.value }), headers: { &quot;Content-Type&quot;: &quot;application/json&quot; } }).then(res =&gt; res.json()).then(res =&gt; { // console.log(res); if (res.ok) { location.href = &quot;/&quot; } else { alert(&quot;用户名密码不匹配!&quot;) } }) } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt;</pre><div class="contentsignin">Copy after login</div></div>

Note: The interface requested in the page is
POST /api/login

Request

Create a new
login.js

in the routes directory. This file defines the page routing of the login page: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>var express = require(&quot;express&quot;); var router = express.Router(); /* GET login page. */ router.get(&quot;/&quot;, function (req, res, next) { res.render(&quot;login&quot;); }); module.exports = router;</pre><div class="contentsignin">Copy after login</div></div>Mount page routing in

app.js

: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class='brush:php;toolbar:false;'>// 引入 var loginRouter = require(&quot;./routes/login&quot;); // 挂载 app.use(&quot;/login&quot;, loginRouter);</pre><div class="contentsignin">Copy after login</div></div>Start the project and visit

http://localhost:3000/login

Normal display:

Node practice: using Cookie&Session for login verification

##2️⃣ Define the API interface in services/UserService.js

Define the model of the interface (

M layer):

const UserService = {
	// .......
    // 登录查询
    login: (username, password) => {
    	// 向数据库查询该用户
        return UserModel.findOne({ username, password });
    },
};
Copy after login
Define the control layer of the interface (C layer

) in

controllers/UserController.js :

const UserController = {
 	// ......
 	// 登录验证
    login: async (req, res, next) => {
        try {
            const { username, password } = req.body;
            const data = await UserService.login(username, password);
            // console.log(data);
            if (data) {
                res.send({ ok: 1, msg: "登录成功!", data });
            } else {
                res.send({ ok: 0, msg: "用户不存在,登录失败!" });
            }
        } catch (error) {
            console.log(error);
        }
    },
};
Copy after login
Define Api

in

routes/users.js:

// 登录校验
router.post("/login", UserController.login);
Copy after login
At this point, the login page is set up:

Node practice: using Cookie&Session for login verification

How login verification works We know from the introduction:

Figure 1Node practice: using Cookie&Session for login verification

This process is obviously more complicated. There is a
in
express

The express-session module can greatly reduce our workload and allow us to stand on the shoulders of giants for development! Downloadexpress-session

npm i express-session
Copy after login
Configure in app.js

:

// 引入express-session
var session = require("express-session");

// 配置session:需要放在在路由配置的前面
app.use(
    session({
        name: "AilixUserSystem", // cookie名字
        secret: "iahsiuhaishia666sasas", // 密钥:服务器生成的session的签名
        cookie: {
            maxAge: 1000 * 60 * 60, // 过期时间:一个小时过期
            secure: false, // 为true时表示只有https协议才能访问cookie
        },
        resave: true, // 重新设置session后会重新计算过期时间
        rolling: true, // 为true时表示:在超时前刷新时cookie会重新计时;为false表示:在超时前无论刷新多少次,都是按照第一次刷新开始计时
        saveUninitialized: true, // 为true时表示一开始访问网站就生成cookie,不过生成的这个cookie是无效的,相当于是没有激活的信用卡
    })
);
Copy after login
After configuration, just You will find that there is a cookie

named

AilixUserSystem in the browser:

This is because Node practice: using Cookie&Session for login verificationexpress-session

will automatically parse

cookie and set cookie to the front end, which is equivalent to 3 and 6 in Figure 1 (the first half: query through SessionId Session), we no longer need to manually operate cookie.

4️⃣ Permission verificationSet when logging in successfullysession

:

// controllers/UserController.js
// ....
// 登录校验
login: async (req, res, next) => {
   try {
       const { username, password } = req.body;
       const data = await UserService.login(username, password);
       // console.log(data);
       if (data) {
           // 设置session:向session对象内添加一个user字段表示当前登录用户
           req.session.user = data; // 默认存在内存中,服务器一重启就没了
           res.send({ ok: 1, msg: "登录成功!", data });
       } else {
           res.send({ ok: 0, msg: "用户不存在,登录失败!" });
       }
   } catch (error) {
       console.log(error);
   }
},
Copy after login
We request # A user

field is added to ##req.session

to save user login information. This step is equivalent to #1 in Figure 1 (SessionId will be express-session Module automatically generated), 2. req.session is a

session
object. It should be noted that although this object exists in

req, it is actually different Their req.session is different when people access the system because req.session is based on the cookie we set (by The generated automatically by the express-session module (AilixUserSystem), and the cookie generated by each person accessing the system is unique, so their req .session is also unique. Verify session when receiving the request, add the following code in

app.js
:

// 设置中间件:session过期校验
app.use((req, res, next) => {
    // 排除login相关的路由和接口
    // 这个项目中有两个,一个是/login的页面路由,一个是/api/login的post api路由,这两个路由不能被拦截
    if (req.url.includes("login")) {
        next();
        return;
    }
    if (req.session.user) {
        // session对象内存在user,代表已登录,则放行
        // 重新设置一下session,从而使session的过期时间重新计算(在session配置中配置了: resave: true)
        // 假如设置的过期时间为1小时,则当我12点调用接口时,session会在1点过期,当我12点半再次调用接口时,session会变成在1点半才会过期
        // 如果不重新计算session的过期时间,session则会固定的1小时过期一次,无论这期间你是否进行调用接口等操作
        // 重新计算session的过期时间的目的就是为了防止用户正在操作时session过期导致操作中断
        req.session.myData = Date.now();
        // 放行
        next();
    } else {
        // session对象内不存在user,代表未登录
        // 如果当前路由是页面路由,,则重定向到登录页
        // 如果当前理由是api接口路由,则返回错误码(因为针对ajax请求的前后端分离的应用请求,后端的重定向不会起作用,需要返回错误码通知前端,让前端自己进行重定向)
        req.url.includes("api")
            ? res.status(401).send({ msg: "登录过期!", code: 401 })
            : res.redirect("/login");
    }
});
Copy after login
Note: This code needs to be in front of the routing configuration.

In this code, we modify the
session

object through

req.session.myData = Date.now();
, thereby triggering

session Update of expiration time (session on myDataThis attribute and its valueDate.now()We just modify session Object tool, itself has no meaning), you can also use other methods, as long as req.session can be modified.

因为我们这个项目是后端渲染模板的项目,并不是前后端分离的项目,所以在配置中间件进行session过期校验拦截路由时需要区分Api路由页面路由

后端在拦截API路由后,向前端返回错误和状态码:

Node practice: using Cookie&Session for login verification

这个时候需要让前端自己对返回结果进行判断从而进行下一步的操作(如回到登录页或显示弹窗提示),该系统中前端是使用JavaScript内置的fetch来进行请求发送的,通过它来对每一个请求结果进行判断比较麻烦,大家可以自行改用axios,在axios的响应拦截器中对返回结果做统一的判断。

5️⃣ 退出登录

向首页(index.ejs)添加一个退出登录的按钮:

<button id="exit">退出登录</button>
Copy after login

为按钮添加点击事件:

const exit = document.getElementById(&#39;exit&#39;)

// 退出登录
exit.onclick = () => {
  fetch("/api/logout").then(res => res.json()).then(res => {
    if (res.ok) {
      location.href = "/login"
    }
  })
}
Copy after login

这里调用了GET /api/logout接口,现在定义一下这个接口,在controllers/UserController.js中定义接口的控制层(C层):

const UserController = {
 	// ......
    // 退出登录
    logout: async (req, res, next) => {
        // destroy方法用来清除cookie,当清除成功后会执行接收的参数(一个后调函数)
        req.session.destroy(() => {
            res.send({ ok: 1, msg: "退出登录成功!" });
        });
    },
};
Copy after login

routes/users.js中定义Api路由:

// 退出登录
router.get("/logout", UserController.logout);
Copy after login

6️⃣ 链接数据库

前面我们通过 req.session.user = data;设置的session默认是存放到内存中的,当后端服务重启时这些session就会被清空,为了解决这一问题我们可以将session存放到数据库中。

安装connect-mongo

npm i connect-mongo
Copy after login

connect-mongoMongoDB会话存储,用于用Typescript编写的连接Express

修改app.js

// 引入connect-mongo
var MongoStore = require("connect-mongo");

// 配置session
app.use(
    session({
        name: "AilixUserSystem", // cookie名字
        secret: "iahsiuhaishia666sasas", // 密钥:服务器生成的session的签名
        cookie: {
            maxAge: 1000 * 60 * 60, // 过期时间:一个小时过期
            secure: false, // 为true时表示只有https协议才能访问cookie
        },
        resave: true, // 重新设置session后会重新计算过期时间
        rolling: true, // 为true时表示:在超时前刷新时cookie会重新计时;为false表示:在超时前无论刷新多少次,都是按照第一次刷新开始计时
        saveUninitialized: true, // 为true时表示一开始访问网站就生成cookie,不过生成的这个cookie是无效的,相当于是没有激活的信用卡
        store: MongoStore.create({
            mongoUrl: "mongodb://127.0.0.1:27017/usersystem_session", // 表示新建一个usersystem_session数据库用来存放session
            ttl: 1000 * 60 * 60, // 过期时间
        }), // 存放数据库的配置
    })
);
Copy after login

至此,我们就实现了运用Cookie&Session进行登录验证/权限拦截的功能!

更多node相关知识,请访问:nodejs 教程

The above is the detailed content of Node practice: using Cookie&Session for login verification. 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 delete node in nvm How to delete node in nvm Dec 29, 2022 am 10:07 AM

How to delete node with nvm: 1. Download "nvm-setup.zip" and install it on the C drive; 2. Configure environment variables and check the version number through the "nvm -v" command; 3. Use the "nvm install" command Install node; 4. Delete the installed node through the "nvm uninstall" command.

How to use express to handle file upload in node project How to use express to handle file upload in node project Mar 28, 2023 pm 07:28 PM

How to handle file upload? The following article will introduce to you how to use express to handle file uploads in the node project. I hope it will be helpful to you!

An in-depth analysis of Node's process management tool 'pm2” An in-depth analysis of Node's process management tool 'pm2” Apr 03, 2023 pm 06:02 PM

This article will share with you Node's process management tool "pm2", and talk about why pm2 is needed, how to install and use pm2, I hope it will be helpful to everyone!

Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Mar 05, 2025 pm 05:57 PM

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

Let's talk about how to use pkg to package Node.js projects into executable files. Let's talk about how to use pkg to package Node.js projects into executable files. Dec 02, 2022 pm 09:06 PM

How to package nodejs executable file with pkg? The following article will introduce to you how to use pkg to package a Node project into an executable file. I hope it will be helpful to you!

What to do if npm node gyp fails What to do if npm node gyp fails Dec 29, 2022 pm 02:42 PM

npm node gyp fails because "node-gyp.js" does not match the version of "Node.js". The solution is: 1. Clear the node cache through "npm cache clean -f"; 2. Through "npm install -g n" Install the n module; 3. Install the "node v12.21.0" version through the "n v12.21.0" command.

What is a single sign-on system? How to implement it using nodejs? What is a single sign-on system? How to implement it using nodejs? Feb 24, 2023 pm 07:33 PM

What is a single sign-on system? How to implement it using nodejs? The following article will introduce to you how to use node to implement a single sign-on system. I hope it will be helpful to you!

Token-based authentication with Angular and Node Token-based authentication with Angular and Node Sep 01, 2023 pm 02:01 PM

Authentication is one of the most important parts of any web application. This tutorial discusses token-based authentication systems and how they differ from traditional login systems. By the end of this tutorial, you will see a fully working demo written in Angular and Node.js. Traditional Authentication Systems Before moving on to token-based authentication systems, let’s take a look at traditional authentication systems. The user provides their username and password in the login form and clicks Login. After making the request, authenticate the user on the backend by querying the database. If the request is valid, a session is created using the user information obtained from the database, and the session information is returned in the response header so that the session ID is stored in the browser. Provides access to applications subject to

See all articles