CORS - jQuery让ajax响应状态失败

时间:2018-05-05 14:10:43

标签: php jquery ajax nginx cors

我遇到了对其他子域的ajax调用问题,请求从 www.mydomain.test 发送到 subdomain1.mydomain.test 。我想处理4xx和5xx错误,因此我可以重定向用户。

从FF或Chromium 执行时,当服务器返回200时,调用完全正常,报告没有CORS问题,但是当服务器返回4xx时,jqXHR.status属性设置为0并且我在控制台上收到以下CORS消息:

Failed to load http://subdomain1.mydomain.test/api.php: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.mydomain.test' is therefore not allowed access. The response had HTTP status code 418.

然而,使用Postman 执行同一个呼叫总是成功,即使服务器返回418或任何其他4xx。

这是JS代码,从www.mydomain.test执行:

$.ajax({
    url : "http://subdomain1.mydomain.test/api.php",
    type : "POST",
    success: function(response)
    {
        redirectToSucessPage();
    },
    error: function(jqXHR, textStatus, errorThrown)
    {
        console.log(textStatus); //prints out "error"
        console.log(jqXHR.status); //prints out 0

        if(jqXHR.status == 401) //never reached
            redirectToErrorPage();
    }
});

这是完整的控制台输出:

POST http://subdomain1.mydomain.test/api.php 418 ()
Failed to load http://subdomain1.mydomain.test/api.php: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://www.mydomain.test' is therefore not allowed access. The response had HTTP status code 418.
error
0

CORS消息并不是很困扰我,虽然我很难搞定它,因为它只发生4xx响应,但我真的需要响应的状态代码。服务器返回418,但jqXHR.status为0。

这是资源的nginx配置:

location = /api.php {                   
    root /path/to/dir;

    add_header 'Access-Control-Allow-Origin' 'http://www.mydomain.test';
    add_header 'Access-Control-Allow-Methods' 'POST';

    limit_req   zone=limitZoneOne   burst=5;

    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}

产生响应的PHP只是:

http_response_code(418) and exit;

我在获得响应状态时是否犯了错误,或者是否存在我不知道的4xx响应的CORS问题?谢谢!

1 个答案:

答案 0 :(得分:0)

在nginx.conf上使用more_set_headers而不是add_header解决:

location = /api.php {                   
    root /path/to/dir;

    more_set_headers 'Access-Control-Allow-Origin:http://www.mydomain.test';
    more_set_headers 'Access-Control-Allow-Methods: POST';

    limit_req   zone=limitZoneOne   burst=5;

    include snippets/fastcgi-php.conf;
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;
}

即使没有Access-Control-Allow-Methods标头,也可以在FF和Chromium上工作。

more_set_headers 指令是HttpHeadersMore模块的一部分,该模块包含在nginx的nginx-extras flavor中,您可以通过执行以下操作将其安装在ubuntu 16上:

  

sudo apt-get install nginx-extras