Express 会话不保存/持久
我不确定我做错了什么 在此之前的最后一个项目很好,会话正在保存/持久
堆栈:MEAN 节点版本:v14.15.0 快捷版:v4.17.1 Express会话版本:v1.17.2
app.ts
// ...
_session: typeof expressSession = require('express-session')
/* Session Store */; this.session_store = new MongoStore({ mongoUrl: this.dbURL });
this.session = this._session({
secret: this.keys,
store: this.session_store,
saveUninitialized: false,
resave: true,
cookie: {
path: '/',
httpOnly: true,
secure: false,
maxAge: 1 * 12 * 60 * 60 * 1000 // 12 hours
},
rolling: true
})
// ...
/* Config */; require('./config.ts');
config.ts
// ...
/* Session Middleware */; app.use((request, response, next) => APP.session(request, response, next));
// ...
login.ts
app.post("/api/login", async (request, response) => {
let body = request.body,
username: string = body.username,
password: string = body.password,
db_account = APP.db.collection("accounts");
if ((!username || !password)) {
if (!request.session["_register"]) return response.sendStatus(411)
username = request.session["_register"].username
password = request.session["_register"].password
// request.session["_register"] = undefined
}
// validator check
if (!validator.isAlphanumeric(username) && !validator.isEmail(username)) return response.status(400).send("username")
// find DB, either username or email
const docs = await db_account.find({ $or: [{ username: username }, { email: username }] }).toArray()
// Not found
if (!docs.length) return response.status(404).json({ error: "username" })
let account: Account = docs[0] as any
if (password != account.password) return response.status(401).json({ error: "password" })
request.session["auth"] = username
console.log(request.session["auth"]) // username attribute exist at this point
return response.status(200).json({ error: null })
})
app.post('/api/auth', async (request, response) => {
console.log(request.session["auth"]); // undefined
request.session["auth"]
? response.send({ auth: true })
: response.send({ auth: false })
})
前端侧 login.component.ts
async login() {
if (this.password.invalid || this.username.invalid) return;
let res: any = await lastValueFrom(this.http.post(server_host() + "/api/login", {
username: this.username.value,
password: md5(this.password),
}))
.catch(err => {
if (err)
return alert("Something went wrong. Please refresh the page and try again.")
})
if (res && !res.error) {
localStorage.setItem("auth", "true")
return this.router.navigate([''])
}
return alert("Something went wrong. Please refresh the page and try again.")
}
前端中间件 app.component.ts
async auth(): Promise<boolean> {
if (!localStorage.getItem('auth')) return false
var res = await lastValueFrom(this.http.post(server_host() + "/api/auth", {}, { withCredentials: true })) as any;
if (!res.auth) { localStorage.removeItem("auth"); return false }
return true
}
// ...
if (ev instanceof NavigationStart) {
//Middleware
this.loading = true;
await this.auth();
}
// ...
在之前的项目中,遵循或多或少相同的模板/工作逻辑,它按预期工作(会话持久/保存) 我哪里做错了?
编辑: 找到了查看所有活动会话的方法 查看express.js中所有当前活动的会话
所以我尝试了为此,
app.post('/api/auth', async (request, response) => {
(request as any).sessionStore.all((err: Error, sessions: any) => {
console.log(sessions);
})
console.log(request.session["auth"]); // still undefined
request.session["auth"]
? response.send({ auth: true })
: response.send({ auth: false })
})
我得到了以下输出:
undefined // from console.log(request.session["auth"]);
[
{
cookie: {
originalMaxAge: 43200000,
expires: '2022-03-21T18:14:12.367Z',
secure: false,
httpOnly: true,
path: '/'
},
auth: 'person'
},
{
cookie: {
originalMaxAge: 43200000,
expires: '2022-03-21T18:16:04.345Z',
secure: false,
httpOnly: true,
path: '/'
},
auth: 'person'
},
{
cookie: {
originalMaxAge: null,
expires: null,
secure: false,
httpOnly: true,
path: '/'
},
auth: 'person1'
},
// the list goes on...
]
这意味着会话已保存,但收到的请求正在使用不同的会话/cookie? 我不确定这里出了什么问题,我正在使用 Angular (平均堆栈)
I'm not sure what I did wrong
Last project before this was fine, session is saving / persisting
Stack: MEAN
Node version: v14.15.0
Express version: v4.17.1
Express session version: v1.17.2
app.ts
// ...
_session: typeof expressSession = require('express-session')
/* Session Store */; this.session_store = new MongoStore({ mongoUrl: this.dbURL });
this.session = this._session({
secret: this.keys,
store: this.session_store,
saveUninitialized: false,
resave: true,
cookie: {
path: '/',
httpOnly: true,
secure: false,
maxAge: 1 * 12 * 60 * 60 * 1000 // 12 hours
},
rolling: true
})
// ...
/* Config */; require('./config.ts');
config.ts
// ...
/* Session Middleware */; app.use((request, response, next) => APP.session(request, response, next));
// ...
login.ts
app.post("/api/login", async (request, response) => {
let body = request.body,
username: string = body.username,
password: string = body.password,
db_account = APP.db.collection("accounts");
if ((!username || !password)) {
if (!request.session["_register"]) return response.sendStatus(411)
username = request.session["_register"].username
password = request.session["_register"].password
// request.session["_register"] = undefined
}
// validator check
if (!validator.isAlphanumeric(username) && !validator.isEmail(username)) return response.status(400).send("username")
// find DB, either username or email
const docs = await db_account.find({ $or: [{ username: username }, { email: username }] }).toArray()
// Not found
if (!docs.length) return response.status(404).json({ error: "username" })
let account: Account = docs[0] as any
if (password != account.password) return response.status(401).json({ error: "password" })
request.session["auth"] = username
console.log(request.session["auth"]) // username attribute exist at this point
return response.status(200).json({ error: null })
})
app.post('/api/auth', async (request, response) => {
console.log(request.session["auth"]); // undefined
request.session["auth"]
? response.send({ auth: true })
: response.send({ auth: false })
})
Front end side
login.component.ts
async login() {
if (this.password.invalid || this.username.invalid) return;
let res: any = await lastValueFrom(this.http.post(server_host() + "/api/login", {
username: this.username.value,
password: md5(this.password),
}))
.catch(err => {
if (err)
return alert("Something went wrong. Please refresh the page and try again.")
})
if (res && !res.error) {
localStorage.setItem("auth", "true")
return this.router.navigate([''])
}
return alert("Something went wrong. Please refresh the page and try again.")
}
Front end middleware
app.component.ts
async auth(): Promise<boolean> {
if (!localStorage.getItem('auth')) return false
var res = await lastValueFrom(this.http.post(server_host() + "/api/auth", {}, { withCredentials: true })) as any;
if (!res.auth) { localStorage.removeItem("auth"); return false }
return true
}
// ...
if (ev instanceof NavigationStart) {
//Middleware
this.loading = true;
await this.auth();
}
// ...
On previous project, following more or less same template / work logic, it works as intended (session persisting / saving)
Where did I go wrong?
EDIT:
found a way to see all active session
View all currently active sessions in express.js
so I tried to do this
app.post('/api/auth', async (request, response) => {
(request as any).sessionStore.all((err: Error, sessions: any) => {
console.log(sessions);
})
console.log(request.session["auth"]); // still undefined
request.session["auth"]
? response.send({ auth: true })
: response.send({ auth: false })
})
I got this output:
undefined // from console.log(request.session["auth"]);
[
{
cookie: {
originalMaxAge: 43200000,
expires: '2022-03-21T18:14:12.367Z',
secure: false,
httpOnly: true,
path: '/'
},
auth: 'person'
},
{
cookie: {
originalMaxAge: 43200000,
expires: '2022-03-21T18:16:04.345Z',
secure: false,
httpOnly: true,
path: '/'
},
auth: 'person'
},
{
cookie: {
originalMaxAge: null,
expires: null,
secure: false,
httpOnly: true,
path: '/'
},
auth: 'person1'
},
// the list goes on...
]
meaning the session IS SAVED but received request is using different session / cookie?
I'm not sure what's wrong here, I'm using Angular (MEAN stack)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
“收到的请求正在使用不同的会话/cookie?”
据我了解,我看到它每次登录时都会创建一个新的 cookie/会话,换句话说,它会创建一个每次登录时持续 12 小时的登录令牌,也许应该解决这个问题,因为它似乎没有'不要覆盖旧的,或者至少替换它们。
"received request is using different session / cookie?"
To my understanding, I see that it creates a new cookie/session each time it logins, in other words, it creates a login token that lasts for 12h EACH time when you login, should probably fix that, as it seems that it doesn't overwrite the old ones, or at least replace them.