我知道问题不是要求PHP代码。因为这个预检事件和Angular2,我到了这里。当我看着Matteo的回答时,我意识到为什么对我的服务器的请求将返回到401.这是因为在预检浏览器中不会发送授权令牌,因此服务器会返回401,并且浏览器认为CORS不被允许。请注意下面的代码只能在开发服务器中使用,除非你知道你在做什么。
在PHP中,你可以这样做:
if (strtolower($_SERVER['REQUEST_METHOD']) === 'options') {
header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Range, Content-Disposition, Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');
echo 'Allowed';
exit;
}
或Nginx的
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
#
# Custom headers and headers various browsers *should* be OK with but aren't
#
add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';
#
# Tell client that this pre-flight info is valid for 20 days
#
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
记住任何其他你发送你必须添加到服务器头接入控制允许头名单。
我阅读了“在ASP.NET Web API中启用跨域请求”的文档,您应该在响应中包含此标头。请参阅此页面中的“CORS如何工作”部分:http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#how-it-works。 –
***我正在关闭它,因为它只是每个OP的打印错误。*** – Win
我认为这个问题在服务器属性中见: http://stackoverflow.com/questions/36825429/angular-2-no -access-control-allow-origin-header-is-present-on-the-requested –