[英]NodeJS / express-session - persist session variables between routes
I am trying to set up session variables that would persist between routes.我正在尝试设置将在路由之间持续存在的会话变量。
Problem is, that doesn't seem to happen.问题是,这似乎没有发生。 When I make a post request, the session variable is updated accordingly - however when trying a different get route via postman (and checking console output), the variable is empty
当我发出发布请求时,会话变量会相应更新 - 但是当通过邮递员尝试不同的获取路由(并检查控制台输出)时,变量为空
Here's the code:这是代码:
const express = require('express')
const session = require('express-session')
const bodyParser = require('body-parser')
const app = express()
app.use(session({
secret: 'test one',
resave: false,
saveUninitialized: true,
name: "mycookiesession",
cookie: { secure: false }
}))
let mySession
app.use(function (req, res, next) {
mySession = req.session
mySession.basket = []
next()
})
app.get('/basket', function (req, res) {
console.log(mySession.basket)
res.send(mySession.basket)
})
app.post('/basket/add', function (req, res) {
mySession.basket = [0, 1, 2]
console.log(mySession.basket)
res.send('null')
res.status(201).end()
})
app.listen(3000, function () {
console.log('Example app listening')
})
What am I doing wrong?我究竟做错了什么? I just need to see the value added to the basket by post:basket/add when retrieving the var in the get:basket route
在 get:basket 路由中检索 var 时,我只需要通过 post:basket/add 查看添加到篮子的值
Cheers干杯
You have a middleware the sets basket = []
in your session for every incoming request.对于每个传入的请求,您的会话中有一个中间件 sets
basket = []
。 This middleware is executed for every request, because the app.use(function ...)
command does not specify a path.这个中间件对每个请求都执行,因为
app.use(function ...)
命令没有指定路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.