CORS - 为什么没有GET请求的响应头

时间:2016-05-29 08:08:37

标签: php jquery cors

我尝试在子域之间实现CORS通信。 POST请求完美地工作,但是在GET请求服务器答案401上,因为没有设置CORS响应头。为什么?

请求JQUERY(简化):

$.ajax({ type:'GET', dataType:'text', url:'https://api.example.com/?something=nice' })

请求标题

GET /?something=nice HTTP/1.1
Host: api.example.com
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Accept: text/plain, */*; q=0.01
Origin: https://subdomain.example.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36
Referer: https://subdomain.example.com/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4

PHP中的响应(简化)

<?php 

if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');
}

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS");

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

    exit(0);
}

echo json_encode($result);

响应头

HTTP/1.1 401 Unauthorized
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Content-Type: text/html; charset=UTF-8
Date: Sun, 29 May 2016 07:44:35 GMT
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Pragma: no-cache
Server: Apache/2.4.18 (Amazon) PHP/5.6.21
X-Powered-By: PHP/5.6.21
Content-Length: 0
Connection: keep-alive

0 个答案:

没有答案
相关问题