I want to make ajax login with the passport.js. I have the usual code for setting the passport.js:
//route
app.post('/api/auth/login', passport.authenticate('local-login', {
successRedirect: '/',
failureRedirect: '/login'
}));
//config strategy
passport.use('local-login', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
}, loginUser));
var loginUser = function(req, email, password, done) {
UserRepo.getOne({
'local.email': email
}).done(function(user) {
if (!user || !user.validPassword(password)) {
return done(null, false, {
message: 'user or password is incorrect'
});
}
return done(null, user);
},
function(err) {
return done(err);
});
};
This is my react
component:
var Login = React.createClass({
//...
handleSubmit: function (e) {
e.preventDefault();
var email = this.state.email.trim();
var password = this.state.password.trim();
var data = {
email: email,
password: password
};
api.auth.login(data, function (result) {
console.log(result);
});
},
render: function () {
return (
<form className="login-form" onSubmit={this.handleSubmit}>
<section>
<label>email</label>
<input name="email" type="text" />
<label>password</label>
<input name="password" type="password" />
</section>
<section>
<input type="submit" value="send"/>
</section>
</form>
);
}
//...
})
But, it doesn't work, because redirects (successRedirect
and failureRedirect
) do their work. If I delete failureRedirect
I get 401
status. I understand that my code for passport
for server side rendering and page refresh, but I cannot find any documentation for ajax login.
You can use a custom callback to return JSON data.
app.post('/api/auth/login', function(req, res, next) {
passport.authenticate('local-login', function(error, user, info) {
if(error) {
return res.status(500).json(error);
}
if(!user) {
return res.status(401).json(info.message);
}
res.json(user);
})(req, res, next);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With