0

I want to be able to redirect my MEAN app to the Login page whenever there is no valid login.

I have a component, which on ngOninit() calls an API route.

The API route looks like:

router.get("/route", isLoggedIn, (req, res) => {
});

Where isLoggedIn is:

function isLoggedIn(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  } else {
    console.log("Not Logged in");
    res.redirect("http://localhost:3000/login");
  }
}

When res.redirect("http://localhost:3000/login") is executed, it throws an error in the console: "Template parse error". I guess this has something to do with the component which called the API waiting for the response from the API.

What's the best way to accomplish this?

2 Answers 2

1

Handle it in your MEAN app, redirect the user to login page from angular and from API return a JSON response.

res.status(401).json({error: "Unauthorized Access"});

In you angular side, in the response of this API call check if you get this error then redirect user to login page. you could do this by using angular service. $location

$location.url('/login');

For generic solution to check authentication on every route you should use http interceptor. Please have look at following stackoverflow question:

AngularJs route authentication

Sign up to request clarification or add additional context in comments.

4 Comments

So I should do this for all the calls? Is there some generic way to do it? Rather than writing this check in all the calls?
@NimishDavidMathew I have updated my answer please have a look I hope it helps .
Yes. Thank you!
@NimishDavidMathew Welcome!
0

If you are using angular then you need to manage to route on the angular side. You can send some sort of HTTP code or response to tell your angular app that request is unauthorized.

You can write general wrapper that send a request to your node server and check for the error. You can write general function according to the logic and library you are using but that would be something like this.

function makeRequest(url,..., callback) {
  request(...).then(response => {
    if(resp.status === 401) $location.url('/login');
    else callback(resp.data)
  })
}

1 Comment

Thanks for helping!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.