简体   繁体   English

使对不同域和基本身份验证的服务器发出ajax POST请求是不可能的?

[英]is making an ajax POST request to a server with a different domain and basic auth impossible?

I am trying to make a POST request to a server with a different domain, that requires basic authentication. 我正在尝试向具有其他域的服务器发出POST请求,该请求需要基本身份验证。

I have tried every combination of beforeSend and withCredentials, but the basic auth headers are never sent through in the OPTIONS preflight request. 我已经尝试过beforeSend和withCredentials的每种组合,但是基本的auth标头从未在OPTIONS预检请求中发送过。

 $.ajax({
      url: anotherdomain,
      data: data,
      cache: false,
      contentType: false,
      processData: false,
      type: 'POST',
      dataType:'json',
      xhrFields: {
         withCredentials: true
      },
      crossDomain: true,
      beforeSend: function(xhr) {
        xhr.setRequestHeader('Authorization', 'Basic *');
          xhr.withCredentials = true;        
      }

The only way i can seem to get this request to succeed is by setting dataType to 'jsonp', or setting the request 'type' to a GET. 我似乎可以使该请求成功的唯一方法是将dataType设置为“ jsonp”,或将请求的“ type”设置为GET。

Is the only solution to this problem to remove the Basic Auth requirement from the anotherdomain server for OPTIONS requests? 解决此问题的唯一解决方案是从其他域服务器中删除OPTIONS请求的基本身份验证要求?

Thanks. 谢谢。

You will have to also allow headers on the server: Here is a php example (this is open for request for all origins, I suggest you limit it only to the site generating the ajax): 您还必须在服务器上允许标头:这是一个php示例(这是开放给所有来源的请求,建议您仅将其限制为生成ajax的网站):

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM