CORS错误-我的标题 [英] CORS error - my headers
问题描述
在问这个问题之前,我已经尝试做作业,但是看不到标题中缺少什么.
I have attempted to do my homework before asking this question but I cannot see what is missing in my headers.
我在javascript中设置了以下标头:
I set the following headers in the javascript:
xhr.setRequestHeader('Access-Control-Allow-Headers', 'Origin, Accept, Content-Type, Access-Control-Allow-Origin');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET,POST');
xhr.setRequestHeader('Content-Type', 'application/json');
服务器发送带有响应的标头:
The server sends the headers with the response:
Pragma: no-cache
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: PUT, GET, POST, OPTIONS
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
Access-Control-Max-Age: 86400
Transfer-Encoding: chunked
Cache-Control: no-store, must-revalidate, no-cache, post-check=0, pre-check=0
Date: Wed, 15 Mar 2017 03:39:49 GMT
Set-Cookie: PHPSESSID=1ng3l10lvrrovlmdbij5chv2f5; path=/
Server: Apache
Content-Type: application/json
Expires: Thu, 19 Nov 1981 08:52:00 GMT
但是我在浏览器(FF和Chrome)中收到错误:
Yet I get the error in my browsers(FF & Chrome):
跨域请求被阻止:同源策略"不允许读取 http://api.mydomain上的远程资源.com/login .(原因:CORS预检频道中的CORS标头"Access-Control-Allow-Headers"中缺少令牌"access-control-allow-headers".
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://api.mydomain.com/login. (Reason: missing token ‘access-control-allow-headers’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel).
任何人都可以看到我所缺少的吗?
Can anyone see what I am missing?
推荐答案
此解决方案似乎效果很好.
This solution seems to work well.
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']) && $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] == 'POST') {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With, content-type, access-control-allow-origin, access-control-allow-methods, access-control-allow-headers');
}
exit;
}
header('Content-type: application/json');
header('Access-Control-Allow-Origin: *');
JavaScript:
Javascript:
xhttp.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
xhttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xhttp.setRequestHeader("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS");
xhttp.setRequestHeader("Access-Control-Allow-Headers", "Content-Type");
xhttp.setRequestHeader("Access-Control-Request-Headers", "X-Requested-With, accept, content-type");
这篇关于CORS错误-我的标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!