jQuery AJAX 头授权

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11540086/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:43:52  来源:igfitidea点击:

jQuery AJAX Header Authorisation

jquerywebtrends

提问by Ryan Brodie

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:

我正在尝试根据本教程授权 AJAX 查询。它在使用 Crypto 库使用适当的授权信息发送之前设置请求标头。我遇到的问题是标题似乎不是根据请求设置的。这是我的代码:

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

回答by Ryan Brodie

The issue was not setting the dataTypeto 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.

这个问题是不设置dataTypeJSONP。由于没有这样做,浏览器将调用解释为标准的 AJAX 请求,这意味着它在同源策略下被阻止。

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

工作代码供参考(感谢@pdeschen 建议使用 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> 

回答by englebart

This finallyseems 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" );
} } );