node:<9>session认证机制

本文介绍了如何使用Express和express-session模块实现服务器端的会话管理,通过登录认证的例子详细阐述了session的工作原理。文章中展示了设置、读取session数据的步骤,并提供了登录、检查和退出登录的完整代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

好了,上一期,我们讲到了浏览器访问服务器,如何认证的问题,使用cookie来识别,那么session就是识别的机器,所以我们这期来讲解一下session的应用;

在浏览器发起请求的时候,服务器收到该请求并且存储了一个cookie,然后再发送一个带有cookie的响应头,下次浏览器发送的时候就会带有这个cookie,然后服务器就会在内存中查找这个记录,如果有的话就响应响应的数据获取;

我们可以创建一个服务器来执行这种认证操作,用到的模块为express和express-sessiom模块:

1、安装两个模块

npm i express@4.17.1
npm i express-session

2、导入模块

//1.1 安装并导入模块
const express = require('express')
const session = require('express-session')

3、创建服务器,这个相信大家都会吧,不会的话就去看之前的博客

const express = require('express')
//1.2 创建一个服务器
const app = express()

//1.5 打开服务器
app.listen(8080,()=>{
    console.log('server  running at http://127.0.0.1:8080')
})

4、创建好了服务器,那么我们就通过浏览器发送post请求,其中带有body对象的表单,通过请求对象获取到表单数据,然后存储到请求对象的session对象中,根据现有的字符串来判断该表单数据是否符合条件:

//登录处理
app.post('/user/login',(req,res)=>{
    if(req.body.username != 'tony' || req.body.password != 1111){
        return console.log('登录失败')
    }else{

        //2.2 保存数据到session对象中
        //注意我们的数据要存储在req上
        req.session.username = req.body.username
        req.session.password = req.body.password

        //2.3 将登录状态返回给浏览器
        res.send({
            statu: 0 ,
            result:'登陆成功'
        })
    }
})

不过在这之前,我们需要挂载一个session中间件,如果没有挂载则不会有session这个对象:
 

//1.4 挂载中间件
app.use(session(
    {
        //这个字符串自定义
        secret:'test',
        resave:false,
        saveUninitialized:true
    }
))

这里除了secret是自己随意定义的字符串外,其他都是固定写法,复制即可;

5、之前我们讲过编码格式的问题,既然要使用表单,不要忘了挂载解析中间件:

//2.1 使用编码中间件
app.use(express.urlencoded({extended:false}))

这个要放在最前面

6、使用postman进行测试,使用命令编译,这里推荐使用 nodemon ./文件名

 可以看到提示成功,我这里提交的表单是和代码数据一致的,如果不一致:

 则会提示登陆失败;

下面是全部代码,除了这些其实还可以挂载很多中间件:

//1.1 安装并导入模块
const express = require('express')
const session = require('express-session')

//1.2 创建一个服务器
const app = express()

//2.1 使用编码中间件
app.use(express.urlencoded({extended:false}))

//1.4 挂载中间件
app.use(session(
    {
        //这个字符串自定义
        secret:'test',
        resave:false,
        saveUninitialized:true
    }
))

//1.3 挂载路由

//登录处理
app.post('/user/login',(req,res)=>{
    if(req.body.username != 'tony' || req.body.password != 1111){
        return console.log('登录失败')
    }else{

        //2.2 保存数据到session对象中
        //注意我们的数据要存储在req上
        req.session.username = req.body.username
        req.session.password = req.body.password

        //2.3 将登录状态返回给浏览器
        res.send({
            statu: 0 ,
            result:'登陆成功'
        })
    }
})

//检查处理
app.post('/user/logincheck',(req,res)=>{
    console.log(
        {
            'username':req.session.username,
            'password':req.session.password
        }
    )

    res.send({
        statu:0,
        result:'检查成功'
    })
})

//退出处理
app.post('/user/loginout',(req,res)=>{
    if(req.body.username == 'tony' && req.body.password == 1111 ){
            req.session.destroy()
            console.log('信息更新')
            res.send(
                {
                    statu:0,
                    result:'用户退出'
                }
            )
    }else{
        res.send(
            {
                statu:1,
                result:'退出失败'
            }
        )
    }
})

//1.5 打开服务器
app.listen(8080,()=>{
    console.log('server  running at http://127.0.0.1:8080')
})

好了,今天就这些内容,欢迎分享

Mar 25 17:40:28.390 mpe_sys: <252> [ DEBUG] The acs :172.28.54.211,port:8080 Mar 25 17:40:28.390 mpe_tr69: <253> [ DEBUG] acs url http://172.28.54.211:8080/openacs/acs(http://172.28.54.127:8080/openacs/acs)! Mar 25 17:40:28.390 mpe_tr69: <254> [ DEBUG] ACS change to http://172.28.54.211:8080/openacs/acs,notify acs! Mar 25 17:40:28.390 mpe_tr69: <255> [ DEBUG] Add 0 BOOTSTRAP success Mar 25 17:40:28.390 mpe_tr69: < 0> [ DEBUG] Add BOOTSTRAP node in event_list success Mar 25 17:40:28.390 mpe_tr69: < 1> [ DEBUG] ACL changed post success Mar 25 17:40:28.390 mpe_tr69: < 2> [ DEBUG] now,have 0 attribute conf Mar 25 17:40:28.390 mpe_tr69: < 3> [ DEBUG] Parameter(InternetGatewayDevice.ManagementServer.URL) is not in attri.conf Mar 25 17:40:31.970 mpe_tr69: < 4> [ DEBUG] Connect Timeout Mar 25 17:40:31.970 mpe_tr69: < 5> [ DEBUG] init HTTP failure. Mar 25 17:40:31.970 mpe_tr69: < 6> [ DEBUG] node M RETRY CONNECT already exists in event_list Mar 25 17:40:31.970 mpe_tr69: < 7> [ DEBUG] close socketfd 67 Mar 25 17:40:31.970 mpe_tr69: < 8> [ DEBUG] Initialize comm failed. Mar 25 17:40:31.970 mpe_tr69: < 9> [ DEBUG] Start session failed. Mar 25 17:40:31.970 mpe_tr69: < 10> [ DEBUG] call event_session() failed. Mar 25 17:40:31.970 mpe_tr69: < 11> [ DEBUG] Wait SEM Connect...... Mar 25 17:40:31.970 mpe_tr69: < 12> [ DEBUG] Session SEM arrive...... Mar 25 17:40:31.970 mpe_tr69: < 13> [ DEBUG] Wait SEM Inform...... Mar 25 17:40:31.970 mpe_tr69: < 14> [ DEBUG] event_code = 0 BOOTSTRAP is in event list Mar 25 17:40:31.970 mpe_tr69: < 15> [ DEBUG] event_code = 2 PERIODIC is in event list Mar 25 17:40:31.970 mpe_tr69: < 16> [ DEBUG] RETRY_CONNECT event existed in the event_list. Mar 25 17:40:31.970 mpe_tr69: < 17> [ DEBUG] retry_interval = 13 Mar 25 17:40:31.970 mpe_tr69: < 18> [ DEBUG] I am waiting at the time:13 s Mar 25 17:40:44.970 mpe_tr69: < 19> [ DEBUG] Haved pass time 13 s Mar 25 17:40:44.970 mpe_tr69: < 20> [ DEBUG] c
03-26
curl -v http://127.0.0.1:50001/login?from=%2F * Trying 127.0.0.1:50001... * Connected to 127.0.0.1 (127.0.0.1) port 50001 (#0) > GET /login?from=%2F HTTP/1.1 > Host: 127.0.0.1:50001 > User-Agent: curl/7.81.0 > Accept: */* > * Mark bundle as not supporting multiuse < HTTP/1.1 200 OK < Server: Jetty(12.0.22) < Date: Tue, 05 Aug 2025 08:08:40 GMT < Vary: Accept-Encoding < X-Content-Type-Options: nosniff < Content-Type: text/html;charset=utf-8 < Expires: 0 < Cache-Control: no-cache,no-store,must-revalidate < X-Hudson: 1.395 < X-Jenkins: 2.516.1 < X-Jenkins-Session: 6f1cd002 < X-Frame-Options: sameorigin < Set-Cookie: JSESSIONID.63f220ac=node0bx3ovcktgo5v1sslw35k6vk0d6.node0; Path=/; HttpOnly; SameSite=Lax < X-Hudson-Theme: default < Referrer-Policy: same-origin < Cross-Origin-Opener-Policy: same-origin < X-Frame-Options: sameorigin < Transfer-Encoding: chunked < <!DOCTYPE html><html lang="en-US"><head resURL="/static/6f1cd002" data-rooturl="" data-resurl="/static/6f1cd002" data-imagesurl="/static/6f1cd002/images"><title>Sign in - Jenkins</title><meta name="ROBOTS" content="NOFOLLOW"><meta name="viewport" content="width=device-width, initial-scale=1"><link rel="icon" href="/static/6f1cd002/favicon.svg" type="image/svg+xml"><link sizes="any" rel="alternate icon" href="/static/6f1cd002/favicon.ico"><link rel="stylesheet" href="/static/6f1cd002/jsbundles/simple-page.css" type="text/css"></head><body class="app-sign-in-register"> <!DOCTYPE html><html><head resURL="/static/6f1cd002" data-rooturl="" data-resurl="/static/6f1cd002" data-extensions-available="true" data-unit-test="false" data-imagesurl="/static/6f1cd002/images" data-crumb-header="Jenkins-Crumb" data-crumb-value="04d8c07d789908f4d48721725a9357683e023527ab8ea30179d66324faf7eb26"> <title>Jenkins - Jenkins</title><link rel="stylesheet" href="/static/6f1cd002/jsbundles/styles.css" type="text/css"><link rel="stylesheet" href="/static/6f1cd002/css/responsive-grid.css" type="text/css"><link rel="icon" href="/static/6f1cd002/favicon.svg" type="image/svg+xml"><link sizes="any" rel="alternate icon" href="/static/6f1cd002/favicon.ico"><link sizes="180x180" rel="apple-touch-icon" href="/static/6f1cd002/apple-touch-icon.png"><link color="#191717" rel="mask-icon" href="/static/6f1cd002/mask-icon.svg"><script src="/static/6f1cd002/scripts/behavior.js" type="text/javascript"></script><script src=&#39;/adjuncts/6f1cd002/org/kohsuke/stapler/bind.js&#39; type=&#39;text/javascript&#39;></script><script src="/static/6f1cd002/scripts/hudson-behavior.js" type="text/javascript"></script><script src="/static/6f1cd002/scripts/sortable.js" type="text/javascript"></script><meta name="ROBOTS" content="INDEX,NOFOLLOW"><meta name="viewport" content="width=device-width, initial-scale=1"><script src="/static/6f1cd002/jsbundles/vendors.js" type="text/javascript"></script><script src="/static/6f1cd002/jsbundles/sortable-drag-drop.js" type="text/javascript"></script><script defer="true" src="/static/6f1cd002/jsbundles/app.js" type="text/javascript"></script></head><body data-model-type="jenkins.install.SetupWizard" id="jenkins" data-search-url="/search/suggest" data-search-help-url="https://www.jenkins.io/redirect/search-box" class="full-screen jenkins-2.516.1" data-version="2.516.1"><div data-help="Help" data-no-results-for="No results for" id="command-palette-i18n" class="i18n" data-get-help="Get help using Jenkins search"></div><dialog id="command-palette" class="jenkins-command-palette__dialog"><div class="jenkins-command-palette__wrapper"><div class="jenkins-command-palette"><div class="jenkins-search-container"><div class="jenkins-search jenkins-command-palette__search"><div class="jenkins-search__icon"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" viewBox="0 0 512 512"><title/><path d="M221.09 64a157.09 157.09 0 10157.09 157.09A157.1 157.1 0 00221.09 64z" fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="32"/><path d="M338.29 338.29L448 448" fill="none" stroke="currentColor" stroke-linecap="round" stroke-miterlimit="10" stroke-width="32"/></svg></div><input autocorrect="off" autocomplete="off" spellcheck="false" id="command-bar" placeholder="Search" type="search" class="jenkins-input jenkins-search__input" autocapitalize="off"></div></div><div id="search-results-container" class="jenkins-command-palette__results-container"><div id="search-results" class="jenkins-command-palette__results"></div></div></div></div></dialog><div id="page-body" class="app-page-body app-page-body--full-screen clear"><div id="main-panel"><a id="skip2content"></a><!-- start of main content ⇒ --><script src="/static/6f1cd002/jsbundles/pluginSetupWizard.js" type="text/javascript"></script><link rel="stylesheet" href="/static/6f1cd002/jsbundles/pluginSetupWizard.css" type="text/css"><form method="POST" action="j_spring_security_check"><input name="from" type="hidden" value="/"><div class="plugin-setup-wizard bootstrap-3"><div class="modal fade in" style="display: block;"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h4 class="modal-title">Getting Started</h4></div><div class="modal-body setup-wizard-heading"><div class="jumbotron welcome-panel offline"><h1>Unlock Jenkins</h1><p>To ensure Jenkins is securely set up by the administrator, a password has been written to the log (<small><a href="https://www.jenkins.io/redirect/find-jenkins-logs" rel="noopener noreferrer" target="_blank">not sure where to find it?</a></small>) and this file on the server: <p><small><code>/var/lib/jenkins/secrets/initialAdminPassword</code></small></p><p>Please copy the password from either location and paste it below.<div class="form-group "><label class="control-label" for="security-token">Administrator password</label><input name="j_username" type="hidden" value="admin"><input name="j_password" id="security-token" type="password" class="jenkins-input "></div></div></div><div class="modal-footer"><input type="submit" class="btn btn-primary set-security-key" value="Continue"></div></div></div></div></div></form><!-- ⇐ end of main content * Connection #0 to host 127.0.0.1 left intact --></div></div></body></html></body></html>root@L4-DriverlessCar:~# 解释一下
最新发布
08-06
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程学渣ズ

谢谢老板

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值