jquery ajax&preemptive basic auth

Gab*_*dez 6 javascript jquery basic-authentication preemptive

我试图达到一些在Apache preemtive基本身份验证下运行的RESTful服务.我正在使用jquery Ajax,并使用'Authentication'标头发送用户和密码.但是,我的请求每次运行时都会抛出一个空错误.

这是完整的$ .ajax调用:

$.ajax({
      cache:false,
      url: urladdress,
      type:'GET',
      async:false,
      headers: { "cache-control": "no-cache" },
      dataType: "html", //or xml or json
      contentType: "html",
       beforeSend : function(req) 
       {
          req.setRequestHeader('Authorization', "Basic " +  base64string); //user:password);
       },
      success: function(data){
         successcallback(data);
      },
      error: function(xhRequest, ErrorText, thrownError){
           alert("ERROR: "+ JSON.stringify(xhRequest));
      },
      complete: function(result){
        ...
      }
});
Run Code Online (Sandbox Code Playgroud)

我做错了什么?有什么我在这里无视的吗?谢谢.

小智 1

解决方案是在服务器端,您必须包含一些自定义标头以响应跨域工作。实验发送以下标头作为响应:

访问控制允许来源:yourApiDomain

访问控制允许方法:*

  • 如果使用自定义标头:

    访问控制公开标头:X-My-Custom-Header、X-Another-Custom-Header

    访问控制允许标头:X-My-Custom-Header、X-Another-Custom-Header

  • 如果使用 HTTP Cookie 和 HTTP 身份验证信息:

    访问控制允许凭据: true

有关更多信息,请阅读MDN 中有关 CORS 的文档: