gpt4 book ai didi

javascript - express-session 不会删除 mongodb 中的 session

转载 作者:行者123 更新时间:2023-12-02 21:24:22 24 4
gpt4 key购买 nike

account.js(node.js部分)

const express = require("express");
const router = express.Router();

router.post("/logout", (req, res) => {
console.log("session: ", req.session);
req.session.destroy();
console.log("session: ", req.session);
res.send(true);
})

session: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZTZjZjJiNDY1N2Q3MjQzNzQxMzFjODkiLCJpYXQiOjE1ODQ3MDM3MDF9.A8-gorvV3SI7boHGbtiRh6NXHbnYIR1VnsAzNWwwMTw
session: undefined

目的:用户登录过程成功。如果登录成功,则将信息保存到mongodb字段中。

enter image description here

问题:当我编写下面这行代码时,通常需要将其删除。但无论我做什么,它都不会删除。您可以通过检查 console.log 部分来理解这一点。

如果你想查看,我在下面的index.js中添加了一些代码。

...
const dotenv = require("dotenv");
const session = require("express-session");
const MongodDBStore = require("connect-mongodb-session")(session);
app.use(cors({ origin: "*" }));
app.set("trust proxy", 1);
const mongoURL = process.env.DB_CONNECT;

var db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function() {});

const store = new MongodDBStore({
uri: process.env.DB_CONNECT,
collection: "sessions"
});

app.use(
session({
secret: process.env.TOKEN_SECRET,
store: store,
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 600000,
sameSite: "strict",
secure: false,
httpOnly: true
}
})
);

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use((req, res, next) => {
res.setHeader("Set-Cookie", "HttpOnly=true;Secure=true;SameSite=None");
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
res.setHeader("Cache-Control", "private");
res.setHeader(
"Access-Control-Allow-Methods",
"GET, PATCH, POST, DELETE , PUT, OPTIONS"
);
next();
});

mongoose.connect(mongoURL, { useNewUrlParser: true, useUnifiedTopology: true });

const server = http.createServer(app);
server.listen(3000);

此删除不会导致。怎么解决呢?

最佳答案

安装cookie-parser模块并将其导入index.js文件

const cookieParser  = require('cookie-parser'); 

并设置中间件

app.use(cookieParser('secret'));

//Middleware for session
app.use(session({
secret: process.env.TOKEN_SECRET,
maxAge: 60000 , // 1min = 60000ms
resave: true,
saveUninitialized: true

}));

关于javascript - express-session 不会删除 mongodb 中的 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60774821/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com