简体   繁体   中英

Jquery - ajax beforeSend basic authentication not working as expected

I am trying to send a request using ajax to a server which is protected by basic authentication with the following code:

$('document').ready(function(){
        $.ajax({
          url: "https://somesite.com/somefolder",
          type: "POST",
          dataType: 'jsonp',
          beforeSend: function(xhr) {
                xhr.setRequestHeader ("Authorization", "Basic " + btoa('myusername' + ":" + 'mypassword'));
            },
          success: function(data){
            console.log('SUCCESS!');
          },
          error: function () {
            console.log("error");
            }
        });         
});

So I provide the credentials in the beforeSend so my expectation would be that there would be no credential popup from the browser since I already provided the credentials but unfortunately when i run this code I get the popup to enter my credentials. I want to the code to provide these credentials.

Similar to this question , example using headers:

    $.ajax({
      url: "https://somesite.com/somefolder",
      type: "POST",
      dataType: 'jsonp',
      headers: {"Authorization": "Basic " + btoa('myusername' + ":" + 'mypassword')},
      success: function(data){
        console.log('SUCCESS!');
      },
      error: function () {
        console.log("error");
        }
    }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM