3

我正在尝试设置一个支持 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 时,萤火虫会显示预期的标头

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:    *

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

4

1 回答 1

4

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

于 2012-01-10T13:16:21.260 回答