我正在处理一个已经有自己基础设施的应用程序,任务是防止用户在多个浏览器中登录。我们的应用程序具有单一应用程序架构,因此理想情况下,用户只应在一个浏览器选项卡中工作。但是我有一个问题。我无法从客户端删除cookie。
I. 简要说明。
应用程序设置:
服务器:NodeJS 端口:8083
客户端:VueJS 端口:8088
我使用模块express-session
在服务器端初始化会话机制并将cookie发送到客户端。客户端没有设置cookie。
II. 详细信息:
服务器的根文件是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
}
}))
正如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
也不管用。
那么,我该怎么解决这个问题?我该做什么?
req.session.Views = null
代码行吗?当您说 Views 时,是指会话设置中的name: SESS_NAME
这样的东西吗?也就是说,我需要写req.session.SESS_NAME = null
吗? - Gleb Tregubovreq.session.SESS_NAME = null
只是在会话存储中添加了新字段。它看起来像这样:Session { cookie: { path: '/', _expires: 2019-10-10T21:08:28.940Z, originalMaxAge: 28800000, httpOnly: true, secure: false, sameSite: false }, userId: 1, blocked: 0, status: 'lambda', SESS_NAME: null }
- Gleb Tregubovreq.session.sid = null
行中明确添加了SESS_NAME,结果与之前相同。只有会话存储中的新行:Session { cookie: { path: '/', _expires: 2019-10-10T21:38:26.600Z, originalMaxAge: 28800000, httpOnly: true, secure: false, sameSite: false }, userId: 489, login: 'glebtregubov', password: '10293221', blocked: 0, status: '392', sid: null }
- Gleb Tregubov