【发布时间】:2020-02-07 05:07:59
【问题描述】:
我使用的应用程序已经拥有自己的基础架构。任务是防止用户在多个浏览器中登录。我们的应用程序具有单一应用程序架构,因此理想情况下用户应该只在一个浏览器选项卡中工作。我有一个问题。我无法从客户端删除 cookie。
我。简要说明。
应用设置:
服务器:NodeJS 端口:8083
客户端:VueJS 端口:8088
我使用模块express-session 在服务器端初始化会话机制并将cookies 发送到客户端。客户端没有设置cookies。
二。详情:
服务器的根文件是index.js
我在里面做了以下事情:
- 插入
express模块:
const express = require('express')
- 插入
cors模块:
const cors = require('cors')
- 添加
cors设置:
app.use(cors({
origin: 'http://localhost:8088',
credentials: true
}))
然后我在 user.js 文件中初始化会话并接收客户端的连接:
- 插入
express-session模块:
const session = require('express-session')
- 通过
express.Router()插入路由:
const router = express.Router()
- 添加会话设置:
const EIGHT_HOURS = 1000 * 60 * 60 * 8
const {
SESS_NAME = 'sid',
SESS_LIFETIME = EIGHT_HOURS,
SESS_SECRET = 'test',
NODE_ENV = 'development'
} = process.env
const IN_PROD = NODE_ENV === 'production'
- 初始化会话:
router.use(session({
name: SESS_NAME,
resave: false,
saveUninitialized: false,
secret: SESS_SECRET,
cookie: {
maxAge: SESS_LIFETIME,
sameSite: false,
// Must have HTTPS to work 'secret:true'
secure: IN_PROD
}
}))
- 通过
router.post()接收客户端查询
所以我做了什么:
- 我使用
req.session.destroy删除会话数据,并希望浏览器注销用户从某些浏览器和cookie 清除。
req.session.destroy(err => {
if (err) {
return res.send({ error: 'Logout error' })
}
res.clearCookie(SESS_NAME, {path: '/'})
return res.send({ 'clearSession': 'success' })
})
不幸的是,没有任何魔法发生
我阅读了不同的主题。例如,这里 (GitHub) 提供了结论:在
res.clearCookie方法中使用显式 cookie 的路径指示,如上所示。 那没用。在 cookie 设置中写入此设置
{path: '/'}。也没有用。
router.use(session({
name: SESS_NAME,
resave: false,
saveUninitialized: false,
secret: SESS_SECRET,
cookie: {
path: '/',
maxAge: SESS_LIFETIME,
sameSite: false,
// Must have HTTPS to work 'secret:true'
secure: IN_PROD
}
}))
正如 express-session 文档 (NPM:express-session) 中所写,此路径是 cookie 存储的默认路径。
- 在 req.session.destroy 中添加
req.session = null:
req.session.destroy(err => {
if (err) {
return res.send({ error: 'Logout error' })
}
req.session = null
res.clearCookie(SESS_NAME, {path: '/'})
return res.send({ 'clearSession': 'success' })
})
没用
-
delete req.session也不行。
那么,我该如何解决这个问题呢?我该怎么办?
【问题讨论】:
标签: node.js express session cookies