开发者

HTTP request header not being set using headers parameter of jQuery.ajax() on Chrome/Safari/Webkit browsers

开发者 https://www.devze.com 2023-03-23 13:51 出处:网络
I am using jQuery 1.6.2 and I am seeing odd behaviour using the headers parameter of the jquery.ajax() method. I am using this parameter to do HTTP Basic Authentication. The request works fine in Fire

I am using jQuery 1.6.2 and I am seeing odd behaviour using the headers parameter of the jquery.ajax() method. I am using this parameter to do HTTP Basic Authentication. The request works fine in Firefox and data is retrieved successfully from a server. However, in Chrome and Safari, I get a prompt to enter a username and password. Looking at the HTTP Request in Chrome, I do not see the开发者_开发技巧 Authorization request header. However, on Firefox, I do.

Any ideas what's going on here and how to remedy this issue?

Update

Here is the code as requested. I've tried using both the pre- and post-1.5 way of setting HTTP Request Headers to no avail.

$(function(){
  $.ajax({
    url: "<some url>", 
    dataType: "jsonp",

    // jquery 1.5+ Approach

    // headers: {
    //   "Authorization":"Basic username:password",
    //   "Content-Type":"application/x-www-form-urlencoded"
    // },


    // jQuery 1.4 Approach

    // beforeSend: function(jqXHR, settings) {
    //  jqXHR.setRequestHeader("Authorization", "Basic username:password");
    //  jqXHR.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    // },

    success: function(data){
       // do stuff
     }
  });
});


What value are you providing for your Content-Type header? If you aren't specifying it, try the following header.

Content-Type:application/x-www-form-urlencoded


I found an answer that worked for me. Taken from

XMLHttpRequest in Chrome Extension with HTTP Authorization continues to send Authorization Header on regular pages

=>

Append an extra ":x" to your Authorization header like this:

xmlReq.setRequestHeader("Authorization", "Basic "+base64_encode(access_token+":x"));

Works in FF and Chrome. Doesn't work in IE9 - I am still investigating on that.

HTH Thomas


I got bitten by this as well as much as I was scratching my head and debugging jQuery, my specific problem seemed to be I was making an http request to a site that enforced HTTPS, so when the browser got the 301 response pointing to the secure version of the site, it seems like the XHR subsystem follows the redirect but drops the headers in the process :(

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号