加载后 express-session 变量发生变化 api

express-session variable is changed after loading api

我是expressjs的新手,我的问题是关于express-session的。

下面是 app.js,在 package.json 中,我安装了 express 和 express-session。

如果我转到 'localhost:3000',在控制台中,req.session.flag 值将像这样更改:


前一个:未定义
后一:1
前两个:1
两个之后:2

之后,如果我转到 'localhost:3000/three',在控制台中,req.session.flag 值将像这样更改:


前三:2
三后:3

如果我此时刷新'localhost:3000/three',req.session.flag的值将是2而不是3。


前三:2
三后:3

为什么会这样? req.session.flag 的值从上一点改为 3,为什么在控制台中它从 2 开始?

如果我转到'localhost:3000',req.session.flag的值也会从2开始,为什么会这样?


前一个:2
后一:1
前两个:1
两个之后:2

谢谢!

var express = require('express');
var session = require("express-session");
var post = require('./routes/post');
var app = express();

var port = 3000;

app.use(session({secret:'fdsadfasdfdsafdsafdsafdsafd', saveUninitialized:false, resave: false}));



app.get('/', function (req, res, next) {
  console.log("********************************");
  console.log("One before: "+req.session.flag);
  req.session.flag = 1;
  console.log("One after: "+req.session.flag);
      next();
},
function (req, res, next) {
    console.log("Two before: "+req.session.flag);
  req.session.flag = 2;
  console.log("Two after: "+req.session.flag);

var html="<!DOCTYPE html><html><head><title>Hello world</title></head><body ><h1>Hello world</h1></body></html>";
  res.send(html); 
});


app.get('/three', function (req, res, next) {
    console.log("********************************");
  console.log("Three before: "+req.session.flag);
req.session.flag = 3;
console.log("Three after: "+req.session.flag);
});


app.listen(port);

会话未保存在您的 /three 端点中。这是因为您没有发回任何回复(甚至没有回复)。

来自 express-session 文档:

Session.save()

Save the session back to the store, replacing the contents on the store with the contents in memory (though a store may do something else--consult the store's documentation for exact behavior).

This method is automatically called at the end of the HTTP response if the session data has been altered (though this behavior can be altered with various options in the middleware constructor). Because of this, typically this method does not need to be called.

There are some cases where it is useful to call this method, for example, long- lived requests or in WebSockets.

由于您不调用 res.send(或简单地 res.end),请求最终会超时并且不会保存会话。

由于 JavaScript 回调的异步性质,express 不能只发送默认响应。您必须始终手动发送一个。