gpt4 book ai didi

node.js - Node>Expressjs res.render 不重定向

转载 作者:太空宇宙 更新时间:2023-11-03 22:47:47 24 4
gpt4 key购买 nike

我正在使用nodejs和express开发应用程序。我有登录页面。我正在发布用户数据,如果没有用户拥有该数据,那么我想重定向页面。但是 res.render 不起作用(我在代码中添加了注释,其中 res.render 位于我的代码中,例如“//如果找不到用户则重定向”。不知道。这是我的代码:

var mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/fuatblog");
var UserSchema = new mongoose.Schema({
name: String,
email: String,
password: String,
age: Number
}),
Users = mongoose.model('Users', UserSchema);
app.post('/sessions', function (req, res) {

console.log(req.body.user.email);
console.log(req.body.user.password);
Users.find({
email: req.body.user.email,
password: req.body.user.password
}, function (err, docs) {
if (! docs.length) {
// no results...

console.log('User Not Found');
//res.status(400);
//Redirect if user not found
return res.render(__dirname + "/views/login", {
title: 'Giriş',
stylesheet: 'login',
error: 'Email or password is wrong.'
});
}

console.log('User found');
req.session.email = docs[0].email;
console.log(req.session.email);
});

return res.redirect('/Management/Index');
});

最佳答案

您希望在无法识别用户时调用的 .render 方法位于异步代码中。这意味着一旦请求到达您的服务器,就会调用 return res.redirect('/Management/Index'); 。但是,一旦从 Users.find 获得结果,您就应该这样做。即:

app.post('/sessions', function (req, res) {

console.log(req.body.user.email);
console.log(req.body.user.password);
Users.find({
email: req.body.user.email,
password: req.body.user.password
}, function (err, docs) {
if (! docs.length) {
// no results...
console.log('User Not Found');
//res.status(400);
//Redirect if user not found
return res.render(__dirname + "/views/login", {
title: 'Giriş',
stylesheet: 'login',
error: 'Email or password is wrong.'
});
}
console.log('User found');
req.session.email = docs[0].email;
console.log(req.session.email);
return res.redirect('/Management/Index');
});

});

关于node.js - Node>Expressjs res.render 不重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20361006/

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