简体   繁体   English

Express.js - 向 req.session.errors 添加自定义对象

[英]Express.js - Adding custom object to req.session.errors

I am using express-validators and express-session to work with my forms.我正在使用 express-validators 和 express-session 来处理我的表单。

in index.js : I redirect to /inscription with errors as an object to show the errors above the fields.在 index.js 中:我将错误重定向到 /inscription 作为对象以显示字段上方的错误。 It works great.它工作得很好。

router.post('/submit-inscription', function (req, res, next) {
req.check('mail', 'Invalid Mail Address').isEmail();
var errors = req.validationErrors();
if (errors) { 
req.session.errors = errors;
req.session.success = false;
res.redirect('/inscription');
}

But then if there is no error, I check if the mail entered doesnt already exists in my my mongodb.但是如果没有错误,我会检查输入的邮件是否已经存在于我的 mongodb 中。

If it does already exist, I would like to redirect to /inscription with a special error.如果它已经存在,我想重定向到 /inscription 并出现特殊错误。 I could do this using a new session parameter, but I would like to do it using the same errors session.我可以使用新的会话参数来做到这一点,但我想使用相同的错误会话来做到这一点。

So I tried :所以我试过:

else { // email already used
error = {location: 'body', msg:"Email address already registered", param:'mail', value:''};
errors.push(error);
req.session.errors = errors;
res.redirect('/inscription');
}

The error I get is : errors.push is not a function.我得到的错误是:errors.push 不是函数。 I guess it is because errors is not an array but an object.我想这是因为错误不是数组而是对象。

So my question is how could I add this custom error to my req.session.errors object ?所以我的问题是如何将这个自定义错误添加到我的 req.session.errors 对象中?

After a discussion with Sohail, thanks a lot to him, he helped me discover from where and how to solve it.与Sohail讨论后,非常感谢他,他帮助我发现了从哪里以及如何解决它。

let error = {location: 'body', msg:"Email address already registered", param:'mail', value:''};
req.session.errors = [error];
res.redirect('/inscription');

You could create a new key in the errors object and then assign it to the session.error .您可以在errors object创建一个新键,然后将其分配给session.error

Example:例子:

errors.newSessionKey = error;
req.session.errors = errors;
res.redirect('/inscription');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM