简体   繁体   English

jQuery ajax和跨域(CORS)和基本身份验证

[英]jQuery ajax and cross domain (CORS) and Basic Authentication

I tried the answers in the suggested possible duplicate question but they didn't change the result. 我尝试了建议的可能重复问题中的答案,但它们没有改变结果。

I've been trying to POST to a remote server's API by ajax from a client on a local PC (testing Chrome and IE), with no success. 我一直试图通过ajax从本地PC上的客户端(测试Chrome和IE)通过POST到远程服务器的API,但没有成功。 Ajax returns an error with status 0 and the server returns 401. Without basic authentication, I confirmed that it worked. Ajax返回状态为0的错误,服务器返回401。如果没有基本身份验证,我确认它可以工作。 But with basic authentication, it never worked. 但是,使用基本身份验证后,它永远无法工作。

Client: 客户:

$.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
    }

Server: 服务器:

<?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";

Could anyone suggest what I might be missing. 谁能建议我可能会想念的东西。 I spent a day for it but couldn't find any working solution. 我花了一天时间,但找不到任何可行的解决方案。

The server is CentOS 6.7 and Apache 2.2.15. 服务器是CentOS 6.7和Apache 2.2.15。

If your remote server setting for Access-Control-Allow-Origin is just set to localhost then it will only work for local requests. 如果将Access-Control-Allow-Origin的远程服务器设置仅设置为localhost,则它将仅适用于本地请求。 Try: 尝试:

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

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

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