【问题标题】:Browser and AJAX response CORS headers differ浏览器和 AJAX 响应 CORS 标头不同
【发布时间】:2012-02-06 14:25:49
【问题描述】:

我正在尝试设置一个支持 CORS 的 API,我可以通过 JavaScript 访问它。

我用来测试的代码是这样的:

$(function(){
get = function(url_fragment)
{
    $.ajax({
        url:        'my_api',
        dataType:   'json',
        cache:      false,
        success:    function(data)
        {
            alert('success');
        },
        error:      function(data)
        {
            alert('failure');
        }
    })
}
get('');
});

这是一个相当简单的 AJAX 请求。

我已经在我的 nginx 配置中启用了 CORS

add_header Access-Control-Allow-Origin *;

当在我的浏览器中访问 API 时,firebug 会显示预期的标头

Access-Control-Allow-Origin *
Connection          keep-alive
Content-Length      59
Content-Type        application/json;charset=utf-8
Server              nginx/1.0.11 + Phusion Passenger 3.0.11 (mod_rails/mod_rack)
Status              200
X-Frame-Options     sameorigin
X-Powered-By        Phusion Passenger (mod_rails/mod_rack) 3.0.11
X-XSS-Protection    1; mode=block

当我在 firebug 中查看 XHR 请求时,CORS 标头不存在:

Connection          keep-alive
Content-Encoding    gzip
Content-Type        text/plain
Server              nginx/1.0.11 + Phusion Passenger 3.0.11 (mod_rails/mod_rack)
Status              403
Transfer-Encoding   chunked
X-Frame-Options     sameorigin
X-Powered-By        Phusion Passenger (mod_rails/mod_rack) 3.0.11

在使用curl 时,我确实收到了正确的标题

$ curl -i my_api
HTTP/1.1            200 OK
Content-Type:       application/json;charset=utf-8
Connection:         keep-alive
Status:             200
X-Powered-By:       Phusion Passenger (mod_rails/mod_rack) 3.0.11
X-Frame-Options:    sameorigin
X-XSS-Protection:   1; mode=block
Content-Length:     61
Server:             nginx/1.0.11 + Phusion Passenger 3.0.11 (mod_rails/mod_rack)
Access-Control-Allow-Origin:    *

不用说,我很困惑为什么这不起作用,有什么想法吗?

【问题讨论】:

    标签: jquery nginx passenger cors


    【解决方案1】:

    add_header 仅适用于新的状态代码(200、204、301、302 或 304)。缺少标头的响应是 403,因此 add_header 不起作用。第三方headers more模块更加灵活,可以为任何状态码添加header。

    【讨论】:

    • 对,这样就解释了标题的差异,但是我假设它返回 403 的原因是因为原始位置不允许?
    • 我不确定它为什么返回 403,但 X-Powered-By 标头让我认为它来自 ruby​​ 应用程序。
    猜你喜欢
    • 2023-01-26
    • 1970-01-01
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    相关资源
    最近更新 更多