无法使CORS工作,获得标题,获得200响应

时间:2018-01-19 23:15:29

标签: php apache .htaccess cors

我正在尝试实现基于PHP和Slim的API,但仍然收到CORS错误“No' Access-Control-Allow-Origin'标头出现在请求的资源上“错误。但显然我已经确定了。

我已经在互联网上搜索过我的api中的CORS。

用于测试的网址:http://www.ricardochen.com/index2.php

我甚至将一切都删除到了这个(php):

<?php
$data = "test";
header('Content-Type: application/json');
echo json_encode($data);
?>

的.htaccess

Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Max-Age "1000"
Header always set Access-Control-Allow-Headers "X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding"
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"

RewriteEngine On
# Some hosts may require you to use the `RewriteBase` directive.
# If you need to use the `RewriteBase` directive, it should be the
# absolute physical path to the directory that contains this htaccess file.
#
# RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]

根据chrome检查员的标题

GENERAL:

Request URL:http://ricardochen.com/index2.php
Request Method:GET
Status Code:200 OK
Remote Address:198.46.81.208:80
Referrer Policy:no-referrer-when-downgrade

响应标头

Access-Control-Allow-Headers:X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding
Access-Control-Allow-Methods:POST, GET, OPTIONS, DELETE, PUT
Access-Control-Allow-Origin:*
Access-Control-Max-Age:1000
Connection:Upgrade, Keep-Alive
Content-Type:application/json
Date:Fri, 19 Jan 2018 23:08:32 GMT
Keep-Alive:timeout=3, max=100
Server:Apache
Transfer-Encoding:chunked
Upgrade:h2,h2c
X-Powered-By:PHP/5.4.45

请求标题

Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding:gzip, deflate
Accept-Language:en
Cache-Control:no-cache
Connection:keep-alive
Cookie:_ga=GA1.2.637285574.1502508699
Host:ricardochen.com
Pragma:no-cache
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36

我已经尝试在php中设置标头,在.htaccess中,在两个不同的共享主机中尝试过,尝试在我的localhost和相同的行为。

请帮忙

2 个答案:

答案 0 :(得分:0)

当执行交叉原始请求时,浏览器会事先发送OPTIONS请求以找出允许的内容,并希望获得响应中的标题,如下所示:

Access-Control-Allow-Headers: Authorization
Access-Control-Allow-Method: OPTIONS, GET, POST, DELETE, PUT
Access-Control-Allow-Origin: *
Allow: OPTIONS, GET, POST, DELETE, PUT

在浏览器看到这些标头后,它知道允许发出GET请求。确保您正确回复OPTIONS

答案 1 :(得分:0)

最后不知道发生了什么,可能我的测试方法就是问题。

它正在发挥作用。

感谢。