jQuery AJAX Header Authorisation

笑着哭i 提交于 2020-01-21 01:57:49

问题


I'm trying to authorise an AJAX query based on this tutorial. It sets the request headers before send with the appropriate authorisation information by using the Crypto library. The problem I'm having is that headers don't seem to be set on request. Here's my code:

beforeSend : function(xhr) {
  var bytes = Crypto.charenc.Binary.stringToBytes(username + ":" + password);
  var base64 = Crypto.util.bytesToBase64(bytes);
  xhr.setRequestHeader("Authorization", "Basic " + base64);
},

回答1:


The issue was not setting the dataType to JSONP. As this was not done the browser interpreted the call as a standard AJAX request which meant it was being blocked under same-origin-policy.

Working code for reference (credit goes to @pdeschen for suggesting Crpyto):

<script type='text/javascript'>
// define vars
var username = '';
var password = '';
var url = '';

// ajax call
$.ajax({
    url: url,
    dataType : 'jsonp',
    beforeSend : function(xhr) {
      // generate base 64 string from username + password
      var bytes = Crypto.charenc.Binary.stringToBytes(username + ":" + password);
      var base64 = Crypto.util.bytesToBase64(bytes);
      // set header
      xhr.setRequestHeader("Authorization", "Basic " + base64);
    },
    error : function() {
      // error handler
    },
    success: function(data) {
        // success handler
    }
});
</script> 



回答2:


This finally seems to work for me. There could be collisions on an individual call basis. Sets this method as a default for future connection options.

//Function( jqXHR jqXHR )
$.ajaxSetup( {beforeSend: function(jqXHR) {
    jqXHR.setRequestHeader( "My-Header", "My-Value" );
} } );


来源:https://stackoverflow.com/questions/11540086/jquery-ajax-header-authorisation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!