jquery $.ajax call results in 401 unauthorized response when in Chrome or Firefox, but works in IE

前端 未结 1 670
故里飘歌
故里飘歌 2020-12-03 22:18

I have a script running on a web page that needs to use the JQuery $.ajax method (currently using jquery 1.7.2) to submit several GET requests to a service endpoint on a dif

相关标签:
1条回答
  • 2020-12-03 23:11

    I came across a jquery forum post that had some additional information regarding this issue. Based on what I found there, I added this to the $.ajax call:

      beforeSend: function (xhr) {
         xhr.setRequestHeader('Authorization', makeBaseAuth(user, pswd));
      }
    

    where makeBaseAuth() uses the btoa() function like this:

       makeBaseAuth: function(user, pswd){ 
          var token = user + ':' + pswd;
          var hash = "";
          if (btoa) {
             hash = btoa(token);
          }
          return "Basic " + hash;
       }
    

    That appears to be working in Chrome now, I'm not getting a login prompt or a 401 response, the request is going through and I get the expected response. I also removed the option xhrFields: { withCredentials: true } as that didn't appear to be necessary. For some reason this isn't working in Firefox yet, and in the Firefox debugger I can't actually get at the javascript to do any decent debugging to see what the problem is, the way this script works is its loaded into a web page as an anonymous script and I don't have any control over that. I have a way to get at the script in IE and Chrome, but not Firefox for some reason. I'll consider this a win just getting it to work in Chrome, thanks to everyone for prodding me in the right direction!

    0 讨论(0)
提交回复
热议问题