Expressjs在出现错误时将主体值传递给Res.Locals
当发生错误时,我试图捕获表单提交时表单输入中的值,然后在错误重定向后将其传递到相同的输入字段中。为了实现这一点,我在POST路由的Expressjs在出现错误时将主体值传递给Res.Locals,express,error-handling,body-parser,Express,Error Handling,Body Parser,当发生错误时,我试图捕获表单提交时表单输入中的值,然后在错误重定向后将其传递到相同的输入字段中。为了实现这一点,我在POST路由的catch()部分将res.locals.errorFormValue设置为req.body,但是当我console.log(res.locals)调用GET路由时,我看不到任何值。我是否将值保存在正确的位置?是否有更好的方法保存POST上的输入字段值并在渲染视图中使用错误 以下是我的邮寄路线: .post(function(req, res){
catch()
部分将res.locals.errorFormValue
设置为req.body
,但是当我console.log(res.locals)
调用GET路由时,我看不到任何值。我是否将值保存在正确的位置?是否有更好的方法保存POST上的输入字段值并在渲染视图中使用错误
以下是我的邮寄路线:
.post(function(req, res){
models.Post.create({
title: req.body.title,
discovery: req.body.discovery,
userId: req.user.userId
}).then(function(){
req.flash('info', 'Post was successfully created.');
res.redirect('/app');
}).catch(function(err){
console.log(err)
console.log(req.body);
res.locals.errorFormValue = req.body;
var errMessage = [];
var errStatusArray = err.errors;
console.log(errStatusArray);
//Push message value in objects to array
for(var prop in errStatusArray){
errMessage.push(errStatusArray[prop].message);
}
errMessage = errMessage.join(" ")
req.flash('error', errMessage);
res.redirect(req.get('referer'));
});
});
});
以下是获得:
.get(function(req, res){
models.DiscoverySource.findAll({
where: {
organizationId: req.user.organizationId
}
}).then(function(category){
console.log(res.locals);
res.render('pages/app/post-create.hbs',{
category: category,
errorMessage: req.flash('error'),
csrfToken: req.csrfToken()
});
});
});
})
查看模板变量:
<p>{{errorFormValue.title}}</p>
<p>{{errorFormValue.discovery}}</p>
{{errorFormValue.title}
{{errorFormValue.discovery}