Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS $http: how to avoid redirect following

In an AngularJS application I make an $http.post call to a server url. The success response of this url is a 30x Redirect, my problem is that $http.post strictly follows this redirect and returns in the success callback the result of the final invocation. I would like to intercept this redirection and manually redirect the user (changing the browser url) to the final page. Is it possibile?

like image 961
Marco Avatar asked Dec 26 '14 09:12

Marco


1 Answers

Accoring to the docs, the $http service is a core Angular service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP.

Knowing that, and knowing the specifications for XMLHttpRequest, it's probably not possible to intercept a redirect.

The W3C spec for XMLHttpRequest says

If the response has an HTTP status code of 301, 302, 303, 307, or 308

If the redirect violates infinite loop precautions this is a network error.

Otherwise, run these steps:

Set the request URL to the URL conveyed by the Location header.

If the source origin and the origin of request URL are same origin transparently follow the redirect while observing the same-origin request event rules.

Otherwise, follow the cross-origin request steps and terminate the steps for this algorithm.

HTTP places requirements on the user agent regarding the preservation of the request method and request entity body during redirects, and also requires end users to be notified of certain kinds of automatic redirections.

So the redirect happens long before Angular can do anything about it, and it can't be stopped.

Another option would be to do the $http call to your own server, and then use something like cURL serverside (depending on what language is used serverside) which can be set to not follow redirects, to get the resource.

like image 195
adeneo Avatar answered Oct 22 '22 10:10

adeneo