You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JQuery V3.6.3设置Authorization头的GET请求失效问题

问题描述
  • 环境:jQuery 3.6.3
  • 请求方式:GET

未添加Authorization请求头时,AJAX请求可正常执行,代码如下:

$.ajax({
  type: "GET",
  url:'https://........../test',
  success: function (data){

  },
  error: function (xhr, ajaxOptions, thrownError, request, error){
    
  }
});

但通过beforeSend设置Basic认证的Authorization头后,请求无法正常工作,代码如下:

$.ajax({
  type: "GET",
  url:'https://........../test',
  beforeSend: function (xhr) {
      xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
  },
  success: function (data){

  },
  error: function (xhr, ajaxOptions, thrownError, request, error){

  }
});

已尝试单独或组合添加以下参数,问题仍未解决:

async: false,
crossDomain: true, 
dataType: "jsonp"
解决方向
  1. 处理跨域预检请求
    添加Authorization头后,浏览器会触发OPTIONS预检请求,若后端未正确配置CORS响应头,请求会被拦截。需要后端设置:

    • 响应头包含Access-Control-Allow-Headers: Authorization
    • Access-Control-Allow-Origin不能设为通配符*,需指定具体域名
  2. 修复Basic认证编码问题
    btoa()无法处理Unicode字符,若用户名或密码包含非ASCII字符,会导致编码错误,可改用以下编码方式:

    btoa(unescape(encodeURIComponent(username + ":" + password)))
    
  3. 改用headers参数直接设置请求头
    替换beforeSend,直接用jQuery AJAX的headers配置项设置认证头,避免潜在的钩子函数问题:

    $.ajax({
      type: "GET",
      url:'https://........../test',
      headers: {
        "Authorization": "Basic " + btoa(unescape(encodeURIComponent(username + ":" + password)))
      },
      success: function (data){},
      error: function (xhr){}
    });
    
  4. 放弃JSONP方案
    JSONP不支持自定义请求头,若接口支持CORS,移除dataType: "jsonp",改用普通AJAX请求配合正确的CORS配置。

内容的提问来源于stack exchange,提问作者Luca Migliori

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 19:42:39