【问题标题】:jQuery ajax and cross domain (CORS) and Basic AuthenticationjQuery ajax 和跨域 (CORS) 和基本身份验证
【发布时间】:2016-01-26 11:34:07
【问题描述】:

我尝试了建议的可能重复问题中的答案,但没有改变结果。

我一直在尝试通过 ajax 从本地 PC 上的客户端(测试 Chrome 和 IE)发布到远程服务器的 API,但没有成功。 Ajax 返回状态为 0 的错误,服务器返回 401。 没有基本身份验证,我确认它有效。但是对于基本身份验证,它从来没有用过。

客户:

$.ajax({
    type : 'POST',
    url : 'http://api-url',
    data : data,
    success : function (response) {
        console.log(response);
    },
    error : function (xhr, status, error) {
        console.log(xhr);
        console.log(status);
        console.log(error);
    },
    beforeSend : function (xhr) {
        xhr.setRequestHeader('Authorization', 'Basic base64username:password');
    },
    xhrFields : {
        withCredentials : true
    }

服务器:

<?php
    header('Access-Control-Allow-Origin: http://localhost');
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, HEAD, OPTIONS');
    header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
    echo "ok";

谁能建议我可能缺少什么。我花了一天的时间,但找不到任何可行的解决方案。

服务器是 CentOS 6.7 和 Apache 2.2.15。

【问题讨论】:

  • 你是用base64编码整个username:password字符串还是只用用户名编码?
  • 我尝试了建议的可能重复问题中的答案,但他们没有改变结果。
  • 是的,我正确编码了用户名:密码。

标签: javascript jquery ajax apache cross-domain


【解决方案1】:

如果您的 Access-Control-Allow-Origin 的远程服务器设置只是设置为 localhost,那么它将仅适用于本地请求。 试试:

header('Access-Control-Allow-Origin:*);

【讨论】:

  • 我想我已经尝试过(但没有成功),但我还是会尝试一下。
猜你喜欢
  • 1970-01-01
  • 2013-09-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-11
  • 2011-07-27
  • 1970-01-01
相关资源
最近更新 更多