Javascript 跨来源资源共享(CORS)问题

Javascript 跨来源资源共享(CORS)问题,javascript,html,jquery,cors,sap-basis,Javascript,Html,Jquery,Cors,Sap Basis,我们有一些web服务返回xml+atom响应。它们托管在SAP NetWeaver网关应用程序服务器上。它们需要基本身份验证才能访问。响应包含以下标题以支持CORS: access-control-allow-origin: * access-control-allow-methods: POST, GET, OPTIONS, PUT, DELETE, HEAD access-control-allow-headers: Content-Type access-control-max-age:

我们有一些web服务返回xml+atom响应。它们托管在SAP NetWeaver网关应用程序服务器上。它们需要基本身份验证才能访问。响应包含以下标题以支持CORS:

access-control-allow-origin: *
access-control-allow-methods: POST, GET, OPTIONS, PUT, DELETE, HEAD
access-control-allow-headers: Content-Type
access-control-max-age: 1728000
我们有一个HTML5应用程序,它使用jquery调用服务,如下所示:

var url = "http://mytesturl.com/test/";
    $.ajax({
        url: url,
        async: true,
        contentType:"application/atom+xml", 
        type: "GET",
        crossdomain: true,
        beforeSend: function (xhr) {
        xhr.setRequestHeader('Authorization', make_base_auth(uname, passwd));
        }
    })
            .done(function( data, textStatus, jqXHR ){alert("success");})
       .fail(function( jqXHR, textStatus, errorThrown ){
            console.log(jqXHR.status);
            alert(errorThrown + jqXHR.status);
        }); 
Failed to load resource: the server responded with a status of 401 (Unauthorized)
Failed to load resource: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8383' is therefore not allowed access.
尽管服务器响应中出现了标题,但我们仍然会收到如下CORS错误:

var url = "http://mytesturl.com/test/";
    $.ajax({
        url: url,
        async: true,
        contentType:"application/atom+xml", 
        type: "GET",
        crossdomain: true,
        beforeSend: function (xhr) {
        xhr.setRequestHeader('Authorization', make_base_auth(uname, passwd));
        }
    })
            .done(function( data, textStatus, jqXHR ){alert("success");})
       .fail(function( jqXHR, textStatus, errorThrown ){
            console.log(jqXHR.status);
            alert(errorThrown + jqXHR.status);
        }); 
Failed to load resource: the server responded with a status of 401 (Unauthorized)
Failed to load resource: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8383' is therefore not allowed access.
用户名(uname)和密码(passwd)正确。如果我尝试使用RestClient之类的工具调用服务,我可以在响应中看到头。我曾尝试在Chrome 31.0版和Safari 6.0.5版中进行测试。我不知道少了什么。任何有助于解决这个问题的建议都是非常好的


谢谢。

您似乎忘记了在允许的标题列表中包含
授权
标题:

access-control-allow-headers: Content-Type, Authorization
您的客户端代码正在发送一个
授权
头(基本的身份验证内容),因此服务器必须在CORS级别明确允许这样做


还要确保服务器实际使用来自客户端的
OPTIONS
verb请求的那些头进行响应。

contentType
选项设置请求正文的
Content-type
头,而不是响应正文。我没有看到您发送任何数据,因此该选项不正确。值得一看-问题可能与
401
错误有关。
Access Control Allow Origin
可能仅在服务器响应
200 OK
时发送,而不是
401 Unauthorized
。我们添加了这个401,并添加了标题作为下面的答案。在此之后,当客户端发出HTTPGET请求时,我可以看到HTTP选项调用发生。选项调用不返回任何数据,并且在响应中不包含访问控制头。GET呼叫从未发生过。有没有办法解决这个问题?我们添加了这个标题。在此之后,当客户端发出HTTPGET请求时,我可以看到HTTP选项调用发生。选项调用不返回任何数据,并且在响应中不包含访问控制头。GET呼叫从未发生过。有办法解决这个问题吗?