我有一个简单的PHP脚本,我正在尝试跨域CORS请求:
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
...
然而,我仍然得到了错误:
Access-Control-Allow-Headers不允许请求报头字段X-Requested-With
我还缺什么吗?
我有一个简单的PHP脚本,我正在尝试跨域CORS请求:
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
...
然而,我仍然得到了错误:
Access-Control-Allow-Headers不允许请求报头字段X-Requested-With
我还缺什么吗?
当前回答
Access-Control-Allow-Headers不允许*作为可接受的值,请参阅Mozilla文档。
您应该发送已接受的报头,而不是星号(如错误所示,第一个X-Requested-With)。
更新:
*现在接受的是Access-Control-Allow-Headers。
根据MDN Web Docs 2021:
值*仅作为没有凭据的请求(没有HTTP cookie或HTTP身份验证信息的请求)的特殊通配符值。在带有凭据的请求中,它被视为没有特殊语义的字面头名称*。注意,Authorization标头不能是通配符,总是需要显式地列出。
其他回答
当我使用angular 4作为客户端,使用PHP作为服务器端时,这些代码就可以完成了。
header("Access-Control-Allow-Origin: *");
许多互联网范围内的描述没有提到指定Access-Control-Allow-Origin是不够的。下面是一个适合我的完整例子:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, DELETE, PUT, PATCH, OPTIONS');
header('Access-Control-Allow-Headers: token, Content-Type');
header('Access-Control-Max-Age: 1728000');
header('Content-Length: 0');
header('Content-Type: text/plain');
die();
}
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
$ret = [
'result' => 'OK',
];
print json_encode($ret);
如果我们不能正确理解CORS的功能,它会成为一个令人头痛的问题。我在PHP中使用它们,它们工作起来没有问题。参考这里
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 1000");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
header("Access-Control-Allow-Methods: PUT, POST, GET, OPTIONS, DELETE");
在.htaccess中添加此代码
在头部添加自定义认证密钥,如app_key,auth_key..等
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers: "customKey1,customKey2, headers, Origin, X-Requested-With, Content-Type, Accept, Authorization"
如果你想从PHP创建一个CORS服务,你可以使用这段代码作为文件中处理请求的第一步:
// Allow from any origin
if(isset($_SERVER["HTTP_ORIGIN"]))
{
// You can decide if the origin in $_SERVER['HTTP_ORIGIN'] is something you want to allow, or as we do here, just allow all
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
}
else
{
//No HTTP_ORIGIN set, so we allow any. You can disallow if needed here
header("Access-Control-Allow-Origin: *");
}
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 600"); // cache for 10 minutes
if($_SERVER["REQUEST_METHOD"] == "OPTIONS")
{
if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_METHOD"]))
header("Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT"); //Make sure you remove those you do not want to support
if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_HEADERS"]))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
//Just exit with 200 OK with the above headers for OPTIONS method
exit(0);
}
//From here, handle the request as it is ok