4

I would like to intercept response from REST request as $httpProvider.interceptors does in agularjs : https://docs.angularjs.org/api/ng/service/$http

I am making a very little interface with jQuery and would not like to use angular just for this. Do you have and Idea ?

Actually my real problem to fix is the same as this one : Dealing with a 301 and location headers for a REST response in cross-domain

But I would like to solve it the same way with jquery.

I tried this without success : (only catch a 0 status never a 301...)

How can I intercept ajax responses in jQuery before the event handler?

To answer V31, I did this :

$.ajaxSetup({
    error: function(jqXHR, textStatus, errorThrown) {
        if (jqXHR.status == 301) {
            alert("Element not found.");
        } else {
            console.log(jqXHR.status);
            console.log("Error: " + textStatus + ": " + errorThrown);
        }
    }
});

Here is my console : console responses

Which says :

XMLHttpRequest cannot load *******. The request was redirected to '**************', which is disallowed for cross-origin requests that require preflight. 
0 
Error: error:  
Community
  • 1
  • 1
BastienSander
  • 1,718
  • 4
  • 24
  • 50
  • Can we see what you have tried already? – Blackunknown Aug 04 '14 at 08:34
  • @KevinB : could you developp a bit more in an answer please ? – BastienSander Aug 04 '14 at 15:09
  • this problem cannot be resolved, other than by removing the redirect. sorry. The issue you are running into is a CORS issue. you can't handle a redirect while using CORS. – Kevin B Aug 04 '14 at 15:13
  • @KevinB : Please see this post : http://stackoverflow.com/questions/24760792/dealing-with-a-301-and-location-headers-for-a-rest-response-in-cross-domain Here I managed to catch the 301 before the redirect with an interceptor with AngularJs ! – BastienSander Aug 04 '14 at 15:23
  • what i meant was you can't stop the error from appearing in the console. you can of course catch the error, which V31's answer shows you how to do. you can then find the headers within the xhr. – Kevin B Aug 04 '14 at 15:25
  • That's true... I thought it wasn't the case in angularjs but it is. – BastienSander Aug 04 '14 at 15:52
  • So the console error doesn't disturb me that much, I would like to prevent firefox to show me a popup saying "this page is trying to redirect you blablabla", do you have an idea ? – BastienSander Aug 04 '14 at 15:59
  • @BastienSander If interpret Question accurately , requirement is to listen for 301 statusCode ? Thanks – guest271314 Aug 04 '14 at 16:49

2 Answers2

1

You can make use of ajaxSetup in order to catch 301 errors, something like this:

$.ajaxSetup({
    error : function(jqXHR, textStatus, errorThrown) {
        if (jqXHR.status == 0) {
            alert("Element not found.");
        } else {
            alert("Error: " + textStatus + ": " + errorThrown);
        }
    }
});

More on jquery ajax setup

UPDATE:

To handle CORS issue you need to enable cross domain calls, something like this:

var app = angular.module('myApp', []);

  app.config(function($httpProvider) {
      //Enable cross domain calls
      $httpProvider.defaults.useXDomain = true;

      //Remove the header used to identify ajax call  that would prevent CORS from working
      delete $httpProvider.defaults.headers.common['X-Requested-With'];
  });

As you have mentioned that the server side code is not in your hand you need to raise a request to that party in order to include these headers in the response of their API call (if not already done)

 'Access-Control-Allow-Origin' => '*', 
 'Access-Control-Allow-Methods' => ['OPTIONS', 'GET', 'POST']  
V31
  • 7,626
  • 3
  • 26
  • 44
  • @bastienSander in the angular interceptor that you created you checking for 0. Updated the answer to have 0 to be checked – V31 Aug 04 '14 at 15:37
  • Actually I thought I didn't have anymore the redirection probleme in AngularJs but I do have! – BastienSander Aug 04 '14 at 15:51
  • So the console error doesn't disturb me that much, I would like to prevent firefox to show me a popup saying "this page is trying to redirect you blablabla", do you have an idea ? – BastienSander Aug 04 '14 at 16:00
  • Ok so you want to gix the cors issue in angularjs right? One more thing ur server is in which language? Or is it a third party api? – V31 Aug 04 '14 at 17:09
  • @BastienSander: I have updated the answer to handle CORS hope your problem get solved using this one – V31 Aug 05 '14 at 08:35
  • The API allows cross domain so even with this I still have the error :s – BastienSander Aug 05 '14 at 09:49
  • You can see it here : http://stackoverflow.com/questions/24760792/dealing-with-a-301-and-location-headers-for-a-rest-response-in-cross-domain. I don't have anything special ecxept the interceptor.. – BastienSander Aug 05 '14 at 10:13
  • I guess I won't fix my problem because it's a CORS limitation when I receive a 301 – BastienSander Aug 05 '14 at 10:14
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/58686/discussion-between-v31-and-bastiensander). – V31 Aug 05 '14 at 10:25
1

If interpret Question at OP accurately , requirement is to perform a task based on statusCode (301) returned from an $.ajax() call ? ; prior to , or instead of success , error callback ?

Appear that the error callback at OP occur after given response statusCode . Piece below should call statusCode callback before any success , error callback that may be attached to $.ajax().

Try

    $.ajaxSetup({
        statusCode: {
            301: function (data, textStatus, jqxhr) {
                var callback = function (name) {
                  $("#results").html(name)
                };
                if (jqxhr.status === 301) {
                // do stuff
                    alert(jqxhr.readyState, jqxhr.getAllResponseHeaders());
                    callback("response: " + String(data || jqxhr.responseText) 
                            + "<br />textStatus: " + textStatus 
                            + "<br />statusCode : " + jqxhr.status 
                            + "<br />statusText : " + jqxhr.statusText);
                };

            }
        }
    });

jsfiddle http://jsfiddle.net/guest271314/D23k2/

See http://api.jquery.com/jquery.ajax/#jQuery-ajax-settings

guest271314
  • 1
  • 15
  • 104
  • 177