How to show custom error messages using passport and expression

I check if email exists at user registration. If the user already exists, I send the error message "Email already exists." But on the front end, the message “Unauthorized” error 401 is displayed. I want to send an error message that I send to the front end from the rear end, but it sends a default message. below, as I check if the user exists and sends an error message,

exports.register = new LocalStrategy({
    usernameField: 'email',
    passReqToCallback: true
}, function(req, email, password, done,res) {
    var newUser = new User({
        email: email,
        password: password,
        name: req.body.fname
    });
    var searchUser = {
        email: email
    };
    User.findOne(searchUser, function(err, user) {
        if (err) return done(err);
        console.log("err "+err);

        if (user) {
            return done(null, false, {
                message: "email already exists"
            });
        }
        newUser.save(function(err) {
        console.log("newUser "+newUser);
            done(null, newUser);
        })
    });
});

I use a passport for authentication,

authRouter.post('/signup', passport.authenticate('local-register'),function(req, res) {
    createSendToken(req.user, res);
});

- , . , . , ,

Object {data: "Unauthorized", status: 401, config: Object, statusText: "Unauthorized"}
+7
2

, , , , data message, LocalStrategy.

:

authRouter.post('/signup', function(req, res, next) {
  passport.authenticate('local-register', function(err, user, info) {
    if (err) { return next(err); }
    if (!user) { 
        res.status(401);
        res.end(info.message);
        return;
    }
    createSendToken(req.user, res);
  })(req, res, next);
});
+8

passReqToCallback = true,

if (!isMatch) { return done({ message: 'Incorrect password' }); }
0

Source: https://habr.com/ru/post/1629139/


All Articles