gpt4 book ai didi

当使用 server.on 检测到 post 请求时,Node.js 返回无法读取属性禁用未定义

转载 作者:太空宇宙 更新时间:2023-11-03 23:55:45 26 4
gpt4 key购买 nike

在 Node Js 中,我有一个应用程序,当应该从站点禁用用户时,我想在其中添加 cookie。

登录.js

app.post('/login/check' (req, res) => {
//check username password and other stuff
// if invalid credentials make increase pass_enter_tries by 1
if (parseInt(req.cookies.pass_enter_tries) >= 5) {
res.cookie('disabled', 'true', {
httpOnly: true,
expires: new Date(Date.now() + 1800000),
signed: true
});

这工作正常,当用户输入 5 次不正确的密码时,它们将被禁用。但真正的问题是当我检测到残疾人时。

app.js

const http = require('http')
, express = require('express')
, app = express()
, server = http.createServer(app);

server.listen(8080);

require('./login')(app);

server.on('request', (req, res) => {
if (req.signedCookies.disabled == 'true') {
return res.sendFile(__dirname + '/disabled.html');
}
});

app.get('/login', (req, res) => {
res.sendFile(__dirname + '/login.html');
});

当用户发布到/login/check 时,即使他们输入了正确的凭据,控制台也会记录:

if (req.signedCookies.disabled == 'true') { ^

TypeError: Cannot read property 'disabled' of undefined

我如何让它只返回 req.signedCookies.disabled = undefined 而不是抛出错误?

最佳答案

这是因为 .signedCookies 是快速请求对象的属性。不是 http.IncomingMessage,它是 request 事件的 req 参数。

您应该使用快速中间件而不是 server.on('request'...) block :

app.use((req, res, next) => {
if (req.signedCookies.disabled == 'true') {
return res.sendFile(__dirname + '/disabled.html');
} else {
next();
}
});

require('./login')(app);

注意:您应该在任何路由之上使用中间件。

关于当使用 server.on 检测到 post 请求时,Node.js 返回无法读取属性禁用未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57315177/

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