Ajax CORS标头错误

时间:2015-03-02 04:42:25

标签: php jquery ajax http-headers cors

我真的很难弄清楚为什么这个CORS请求被拒绝了。这让我发疯了。它给出了一个错误" NetworkError:500内部服务器错误 - http://api.example.com/v1/users/me"然后是关于Firebug中跨域/ CORS的消息。

JQuery的

jQuery(document).ready(function(){

        var settings = {
            headers: {
                'Authorization': 'Token token= 12345'
            },
            type: 'GET',
            dataType: 'json'
        };

        var deferred = jQuery.ajax('http://api.example.com/v1/users/me', settings).then(
            function(data) {
                console.log(data);            
            }, function(error) {
                console.log(error);
            }
        );

});

请求标题

OPTIONS /v1/users/me HTTP/1.1
Host: api.example.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:35.0) Gecko/20100101 Firefox/35.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Origin: http://fiddle.jshell.net
Access-Control-Request-Method: GET
Access-Control-Request-Headers: authorization
Connection: keep-alive

响应标题

HTTP/1.0 500 Internal Server Error
Date: Mon, 02 Mar 2015 04:28:29 GMT
Server: Apache/2.2.22
X-Powered-By: PHP/5.5.21
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Access-Control-Allow-Origin: http://fiddle.jshell.net
Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE
Access-Control-Allow-Headers: authorization
Set-Cookie: PHPSESSID=dfa4a0638bcf104d316f7358153bb2f9; path=/
Vary: User-Agent
Content-Type: application/json
X-Cache: MISS from 172.19.134.2
X-Cache-Lookup: MISS from 172.19.134.2:3128
Via: 1.0 172.19.134.2:3128 (squid/2.6.STABLE14)
Connection: close

如果有人有兴趣,我在PHP中有这个:

PHP

// Set Headers
header('Access-Control-Allow-Origin: http://fiddle.jshell.net');
header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE');
header('Access-Control-Allow-Headers: authorization');      
header('Content-Type: application/json; charset=utf-8');    

1 个答案:

答案 0 :(得分:0)

我强烈怀疑CORS因为从服务器返回的HTTP 500代码而失败。因此,尽管响应包含CORS的有效信息,但客户端会忽略由于消息代码指示响应无效而导致的信息。

为什么返回500,取决于您的服务器配置/应用程序。