22

I have a web service that is willing to output gzip/deflated data. I've verified that the service will respond with raw JSON or with gzip'd JSON using wget and curl.

I want to consume this web service using the jQuery AJAX call.

By default, the $.ajax call that jQuery provides does not add the "Accept-Encoding: gzip" HTTP request header that's necessary for the web server to respond with gzipped data.

However, when I use jQuery's own methods to add the header, eg:

$.ajax({url: 'http://foo.com/service.json',
        beforeSend: function(xhr) { 
            console.log('xhr set'); 
            xhr.setRequestHeader('Accept-Encoding', 'deflate') 
       } 
});

then the following error appears in the browser console:

Refused to set unsafe header "Accept-Encoding"

Is it possible to force jQuery to make AJAX calls for URLs with gzip/deflate enabled?

If not, is this a shortcoming in jQuery, or something more fundamental with AJAX?

Lee
  • 905
  • 2
  • 9
  • 19
  • 1
    I think the browser decides wether it accepts gzip/deflate or not. "Faking" this could lead to data corruption. – jwueller Sep 23 '10 at 13:19

1 Answers1

41

Browsers automatically add the accept-encoding header as appropriate, including on XHR requests. You don't need to do that at the DOM/JS level.

Dave Ward
  • 59,815
  • 13
  • 117
  • 134
  • thanks, you're right! I should have checked my server logs more closely. – Lee Sep 23 '10 at 13:30
  • Is this true for HTML5 Hybrid applications also? Running on mobile devices, in a webview container....? – demaniak Dec 11 '14 at 10:14
  • @demaniak: It should be, yes. Are you seeing different behavior in a particular webview? – Dave Ward Dec 11 '14 at 14:51
  • @DaveWard - I suspect Android 4.3 webview (on the admittedly custom device) I am working on might not have been adding Accept-Encoding headers. However, I will try to verify this first ;) Any tips apart from Weinre to examine what is happening under the hood? Assume I can't access the backend server to examine incoming requests there. – demaniak Dec 11 '14 at 20:25
  • @demaniak: I would probably proxy the Android device through Fiddler (or Charles on a Mac) on my local machine (e.g. http://encosia.com/using-an-iphone-with-the-visual-studio-development-server/) to inspect the real traffic. – Dave Ward Dec 12 '14 at 00:23