嘿,我想确保是否在我的简单Express应用程序中为中间件使用正确的方式,我正在尝试查找唯一的电子邮件进行注册 这是我的示例
const isUnique = (req, res, next) => {
User.findOne({
where:{
email: req.body.email
}
})
.then(getUser => {
if(getUser){
next("/userAlreadyExist") // router
// or can i render to to html? i am using ejs
} else {
next()
}
})
.catch(next())
}
app.post('/register', isUnique ,(req, res) => {
res.send(`thank you for register`)
}
我想确保电子邮件已经存在或不存在,所以我想首先在中间件上传递它,并获得isUnique
的页面(如果该电子邮件已在使用中),我想将其重定向到名为'/emailExist'
的下一个路由器,如果成功,我想将其重定向到路由器/success
如果代码错误或没有,谁能帮助我?只想确保:D
答案 0 :(得分:2)
您有很多选择,这里有几个。
/emailAlreadyExists
和/registerSuccess
路由中,您可以呈现所需的任何模板或返回一些数据。const isUnique = (req, res, next) => {
User.findOne({
where:{
email: req.body.email
}
})
.then(getUser => {
if (getUser) {
res.redirect('/emailAlreadyExists');
} else {
res.redirect('/registerSuccess'); // or just call next()
}
})
.catch(next("DB error"));
}
const isUnique = (req, res, next) => {
User.findOne({
where:{
email: req.body.email
}
})
.then(getUser => {
req.user = getUser;
next();
})
.catch(next());
}
app.post('/register', isUnique ,(req, res) => {
if (req.user) {
res.send('User already exists');
} else {
res.send(`thank you for register`);
}
}
const isUnique = (req, res, next) => {
User.findOne({
where:{
email: req.body.email
}
})
.then(getUser => {
if(getUser){
next("Error: user already exists"); // or some other error message/object
} else {
next(); // continue to next middleware
}
})
.catch(next("DB error")); // handle errors throw from DB read
}
app.post('/register', isUnique ,(req, res) => {
res.send(`thank you for register`)
}
/*
If you call "next" with an argument, Express will skip
straight to this error handler route with the argument
passed as the "err" parameter
*/
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send(`An error occurred: ${err}`);
})