a.toLowerCase 将 CORS 添加到 ajax header

a.toLowerCase when add CORS to the ajax header

我有一个在线 Django 应用程序和一个 API,需要将特殊的 token 添加到 header。

当我将它添加到 $.ajaxSetup 时,它仍然需要我在 header 中输入 CORS Access-Control-Allow-Origin 参数。

添加时出现错误:TypeError: a.toLowerCase is not a function

奇怪的是,当我在我的 HttpRequester firefox 插件中使用相同的代码时,因为我得到了预期数据的正确响应。

代码:

$.ajaxSetup({
    beforeSend: function(xhr) {
        xhr.setRequestHeader({
          'CORS': 'Access-Control-Allow-Origin',
          'token': 'tokenStringHere'
        });
    }
});

$.ajax({
  url: 'myPathToOnlineAppWithApiString',
  type: 'GET',
  contentType: 'application/json',
  headers: {
  }
}).success(function(result){
  console.log('yes!');
}).error(function(error){
  console.log('no!');
});

setRequestHeader 接受两个字符串,header 名称及其值,而不是 object。有关详细信息,请参阅 jQuery 文档的 $.ajax 条目的 jqXHR 部分。

您应该将参数中的 object 替换为两次调用以单独设置那些 header:

$.ajaxSetup({
     beforeSend: function(xhr) {
        xhr.setRequestHeader('CORS', 'Access-Control-Allow-Origin');
        xhr.setRequestHeader('token', 'tokenStringHere');
    }
});