Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling http 302 redirect responses

I know that http 302 responses are handled directly by the browser, and because of that you cannot acces any of the request properties from your source code. But I am wondering if there is any way of intercepting the 302 redirect response. Let me explain myself:

  1. My Frontend (Angular) makes an http request to A (I intercept the outgoing request)
  2. A responds with 302 Location: B
  3. My Frontend intercepts the 302 response with empty fields, and goes to B
  4. Here I'd like to intercept the response coming from B

This is my Angular http interceptor code:

@Injectable()
export class CasInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log('->Interceptor');
    console.log(req);
    return next.handle(req).map((event: HttpEvent<any>) => {
        const response = event as HttpResponseBase;
        console.log('<-Interceptor');
        console.log(response);
        return event;
    });
  }
}
like image 793
gmc Avatar asked Feb 05 '18 09:02

gmc


People also ask

Does a 302 automatically redirect?

What is an HTTP 302? The 302 status code is a redirection message that occurs when a resource or page you're attempting to load has been temporarily moved to a different location. It's usually caused by the web server and doesn't impact the user experience, as the redirect happens automatically.

How does Google handle 302 redirects?

302 redirects tell Google that a page has moved temporarily. So usually, it keeps the old URL indexed and shows it in the search results. After all, there's no point in removing the old URL and indexing the new URL if the old URL will be back soon. Link signals also usually consolidate “backward” to the old URL.

How do you handle a 302 response in Java?

An HTTP 302 is a 'temporary redirect'. You need to handle it. You need to extract the new URL from the response. (Use getHeaderField("Location") to do this).


1 Answers

You should get full header from http response.

{observe:"response"} is the magic parameter of angular http client. So try this one

this.http
.get<any>(requestURL,{observe:"response"})
.subscribe(
  data => {
    console.log(data.header); //you will see full header here
    console.log(data.url); // you can see redirect url from backend and handle it whatever you want
  },
  err => {
     console.log(err)
  }
like image 146
Tolui Davaasuren Avatar answered Sep 18 '22 15:09

Tolui Davaasuren