Tuesday, October 10, 2017

Passport.js Redirect from express.js to angular 2 not working

I’m trying to redirect to an angular page after login where the login functions are coded in express.js.

router.post('/api/login', function(req, res, next) {
 passport.authenticate('local', function(err, user, info) {
  if (err) {
    return next(err); // will generate a 500 error
  }
  if (! user) {
    //return res.send({ success : false, message : 'login failed' });
    res.redirect('/api/login');
  }
  //return res.send({ success : true, message : 'login succeeded' });
  res.redirect('/dashboard');
 })(req, res, next);
});

After form submit, the console shows this error:

zone.js:2744 GET http://localhost:4200/dashboard 404 (Not Found)

core.es5.js:1020 ERROR Response {_body: "<!DOCTYPE html>↵<html lang="en">↵<head>↵<meta char…<pre>Cannot GET /dashboard</pre>↵</body>↵</html>↵", status: 404, ok: false, statusText: "Not Found", headers: Headers, …}

I’ve commented and checked that the login is successful, and the success redirect fires, but just doesn’t redirect. Is this because I’m trying to redirect from express to angular?

I have my route for dashboard set as

router.get('/dashboard', (req, res) => {
  res.sendFile(path.resolve(__dirname, '../dist/index.html'));
});

When I manually go to /dashboard, the page loads fine. It just gives a 404 while trying to redirect. What am I doing wrong?

Source: AngularJS



from Angular Questions https://angularquestions.com/2017/10/10/passport-js-redirect-from-express-js-to-angular-2-not-working/
via @lzomedia #developer #freelance #web #lzomedia.com

No comments:

Post a Comment