javascript - 跨源资源共享 (CORS) 问题

标签 javascript html jquery cors sap-basis

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

尽管服务器响应中出现了 header ,但我们继续收到如下 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 之类的工具调用该服务,我可以在响应中看到 header 。我已尝试在 Chrome 版本 31.0 和 Safari 版本 6.0.5 中进行测试。我不确定缺少什么。任何有助于解决问题的建议都会很棒。

谢谢。

最佳答案

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

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

您的客户端代码正在发送一个 Authorization header (基本身份验证内容),因此服务器必须在 CORS 级别明确允许这样做。

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

关于javascript - 跨源资源共享 (CORS) 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20859118/

相关文章:

javascript - jQuery AJAX 分页不起作用

javascript - sap.m.面板: make entire header clickable

javascript - 相同的按钮具有相同的效果 - jquery OOP

JavaScript 按降序排列日期的排序列表

php - 如何更新特定 ID 以接受或拒绝用户

html - 显示 : block; has no effect on @media (max-width: 320px)

html - 如何使我的左侧选项卡向左浮动,但将空白区域填充到向右浮动的其他选项卡?

jquery - 在 div 及其子元素上设置不同的 Css3 转换速度

javascript - 如何将选择框的选项值作为占位符字段显示到另一个 html 文件?

php - 验证序列中的表单字段