How to handle 302 in angular 2
Late answer I know, but for anyone stumbling across this.
The short answer is you can't as the browser handles 302's itself and won't tell angular anything about that. What you can do is set-up an interceptor style class that monitors what is going on.
Google for angular2 http interceptor or similar, it's a little beefier than your example above and can monitor every XHR connection. An example is here:
https://www.illucit.com/blog/2016/03/angular2-http-authentication-interceptor/
What this now allows is that any connection will come through your interceptor. As we won't be able to monitor 302s, we have to think about what might happen. For example in my example the request suddenly changes the url to something with my auth in it.
Great so my 1st bit of pseudo code would be:
if (response.url.contains('my-auth string')) {
redirect....
}
I can also see on the headers provided that instead of application/json I've suddenly gone to text/html. Hmm, that's another change I can check for:
if (response.url.contains('my-auth string') && response.headers['content-type'] == 'text/html') {
redirect....
}
You may have other parameters you can check, however these were good enough to detect a redirect for me. Admittedly this is with respect to being redirected to login and not another example, hopefully you get enough distinct changes check for you to decide whether you have got a 302.
Arun Tyagi
Updated on June 16, 2022Comments
-
Arun Tyagi 6 months
I am getting error with status 302 But while trying to log error in catch I am getting 200
post(url, data, successCallBack, errCallback) { return this.http.post(apiDomain + url, JSON.stringify(data), { headers: this.headers }).catch(this.handleError).subscribe( (res) => { successCallBack(res.json()); }, (err) => { errCallback(err); } ); } private handleError(error: any) { let errMsg = (error.message) ? error.message : error.status; console.log(error.status); // log is 200 console.log(error) console.error(errMsg); return Observable.throw(errMsg); }
Requirement I want to send another post call on redirect URL redirects. How to get Redirect URL.
Need help.