其他分享
首页 > 其他分享> > jQuery-浏览器和AJAX响应CORS标头不同

jQuery-浏览器和AJAX响应CORS标头不同

作者:互联网

我正在尝试设置一个可以通过JavaScript访问的启用CORS的API.

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

$(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

当我在萤火虫中查看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:    *

不用说,我对为什么这样不起作用感到困惑,有什么想法吗?

解决方法:

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

标签:nginx,cors,passenger,jquery
来源: https://codeday.me/bug/20191101/1986606.html