Newbie react question: I’m using it with passport.js and express. I’m successfully logging in to the application. But I don't know how to do a redirect.
router.post('/login',
passport.authenticate('local'),
function(req, res) {
// If this function gets called, authentication was successful.
res.redirect('/upload'); //<—— what I’d like to do is some kind of redirect here
});
Any help appreciated.
Do that on your callback route.
router.get('/facebook', passport.authenticate('facebook', { scope: ['public_profile', 'email'] }));
router.get('/facebook/callback',
passport.authenticate('facebook', { failureRedirect: "/" }), function (req, res) {
if (req.user || req.session.user)
return res.redirect('/' + req.user._id || req.session.user._id);
return res.redirect('/login');
});
Here, I have used passport.js for Facebook Login. and in /facebook/callback I have redirected to /login and in /login I have a function to check if the session is set.
if (Helper.isLoggedIn(req)) {
res.redirect('/');
return;
}
Definition of isLoggedIn inside Helper.js is
function isLoggedIn(req) {
if (req.session && req.session.user_email && req.session.user_email != null) {
if (!req.user || req.session.user == undefined || req.session.user == null) {
loadUserFrom(req);
}
return true;
}
return false;
}
May be you can consider to do the redirect in react-js after the getting the response from server. Assume you use the redux-thunk.
action.js:
import axios from 'axios';
import { browserHistory } from 'react-router';
export function signinUser({ email, password }) {
return function(dispatch) {
axios.post(`${ROOT_URL}/signin`, { email, password })
.then(response => {
// Successful login, redirect to /upload
browserHistory.push('/upload');
})
.catch(() => {
//handle the error response from server
});
}
}