简体   繁体   中英

Express.js - Adding custom object to req.session.errors

I am using express-validators and express-session to work with my forms.

in index.js : I redirect to /inscription with errors as an object to show the errors above the fields. 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.

If it does already exist, I would like to redirect to /inscription with a special error. 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. 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 ?

After a discussion with Sohail, thanks a lot to him, he helped me discover from where and how to solve it.

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 .

Example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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