gpt4 book ai didi

node.js - 检查 session 时无法读取未定义的属性 "name"

转载 作者:太空宇宙 更新时间:2023-11-04 00:06:27 25 4
gpt4 key购买 nike

所以我是表达新手,我制作了某种程序,仅在您成功登录时才注册 session ,然后在其他路由中使用它来应用不同的内容,具体取决于 session 是否存在。

但是,问题是它给了我一个错误

Cannot read property "name" of undefined
为什么?我什至登录成功,所以 session 应该存在,对吗?

这是代码:

// Importing modules/packages
let connection = require("./Connection.js");
let bodyParser = require("body-parser");
var cookieParser = require("cookie-parser");
let express = require("express");
let app = express();
var session = require("express-session");
app.use(cookieParser());
app.use(
session({
secret: "1E3ESS3DSS4DS4",
saveUninitialized: true,
resave: false,
cookie: {
path: "/",
maxAge: 1000 * 60 * 60,
httpOnly: true
}
})
);
let urlencodedParser = bodyParser.urlencoded({ extended: false });

// Server and routing
app.listen(3000, function() {});
app.set("view engine", "ejs");
app.get("/Signup", (req, res) => {
res.render("Register");
});
app.get("/", function(req, res) {
if (
typeof req.session.user.name == "undefined" &&
typeof req.session.user.password == "undefined"
) {
res.render("Home");
}
res.redirect("Login");
});
app.get("/Login", function(req, res) {
res.render("Login");
});

// Database's Connection
connection.connect(err => {
if (err) {
throw "ERROR! " + err;
}
});

// Requesting and Receiving Data from body parser
app.post("/Signup", urlencodedParser, function(req, res) {
res.render("Register");
connection.query(
`insert into users (Username, User_Password, Email_Address) values ("${
req.body.Username
}", ${req.body.Password}, "${req.body.Email}")`,
function(err) {
if (err) throw "An error has happened while excuting the query " + err;
}
);
});

app.post("/Login", urlencodedParser, (req, res) => {
let sess = req.session;
connection.query(
`SELECT Username FROM users WHERE User_Password = ? AND Username = ?`,
[req.body.Password, req.body.Username],
function(err, results) {
if (results.length === 0) {
console.log(
"Sorry, this username/password doesn't exist in our database."
);
} else {
sess.user = {
name: req.body.Username,
password: req.body.Password,
online: true
};
req.session.save();
}
res.render("Login");
}
);
});

如何修复它?

最佳答案

您必须检查整个路径是否存在,而不仅仅是最后一个属性。如果 user 不是 object,则即使 typeof 也会失败,因为它尝试访问 undefined 的属性。

app.get("/", function(req, res) {
if (
typeof req.session.user != "object" || (
typeof req.session.user.name == "undefined" &&
typeof req.session.user.password == "undefined")
) {
res.render("Home");
}
res.redirect("Login");
});

关于node.js - 检查 session 时无法读取未定义的属性 "name",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52019956/

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