2

我们有一些 Web 服务返回 xml+atom 响应。这些托管在 SAP NetWeaver Gateway 应用服务器上。它们需要基本身份验证才能访问它们。响应包含以下标头以支持 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);
        }); 

尽管服务器响应中包含标头,但我们继续收到如下 CORS 错误:

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 版中进行测试。我不确定缺少什么。任何有助于解决问题的建议都会很棒。

谢谢。

4

1 回答 1

3

您似乎忘记Authorization在允许的标头列表中包含标头:

access-control-allow-headers: Content-Type, Authorization

您的客户端代码正在发送Authorization标头(基本身份验证内容),因此服务器必须在 CORS 级别明确允许此操作。

还要确保服务器实际上使用这些标头响应OPTIONS来自客户端的动词请求。

于 2013-12-31T15:04:31.987 回答