Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular - how to handle redirect

I use spring security, which redirects unauthenticated users to a login page.

So when an unauthenticated angular client sends a GET request to an endpoint (expecting JSON), it receives the HTML content of the login page, and the JSON parser fails (Angular2 watch for 302 redirect when fetching resource)

const httpObservable = this.http.get(urlThatWillRedirect).subscribe(data => ...) // JSON parser will fail

How can I handle redirects in Angular?

like image 818
nagy.zsolt.hun Avatar asked Sep 12 '18 08:09

nagy.zsolt.hun


People also ask

What is redirect in angular?

When the application start, it navigates to the empty route by default. We can configure the router to redirect to a named route by default. So, a redirect route translates the initial relative URL (”) to the desired default path.


1 Answers

The correct solution is to change the server side code to not return 302 status codes because browser kicks in the redirect before Angular (or any SPA for that matter) can do anything about it. Usually, you want to return 401/403s for this very purpose.

If this is not possible, the only alternative is to implement a hackish solution to somehow recognize that the response is indeed a redirect and handle it appropriately by using HttpInterceptors. Here's an equivalent example in AngularJS.

In Angular 2+, you could probably follow something like this to check if the response is a redirected page:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(req)
      .do(event => {
        if (event instanceof HttpResponseBase) {
          const response = event as HttpResponseBase;
          if (response && response.ok && response.url && response.url.toLowerCase().indexOf(this.logoPartialUrl) >= 0) {
            // Modify this portion appropriately to match your redirect page
            const queryStringIndex = response.url.indexOf('?');
            const loginUrl = queryStringIndex && queryStringIndex > 0 ? response.url.substring(0, queryStringIndex) : response.url;
            console.log('User logout detected, redirecting to login page: %s', loginUrl);
            window.location.href = loginUrl;
          }
        }
      });
like image 53
l46kok Avatar answered Oct 28 '22 09:10

l46kok