我有一个简单的PHP脚本,我正在尝试跨域CORS请求:

<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
...

然而,我仍然得到了错误:

Access-Control-Allow-Headers不允许请求报头字段X-Requested-With

我还缺什么吗?


当前回答

在.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"

其他回答

Access-Control-Allow-Headers不允许*作为可接受的值,请参阅Mozilla文档。

您应该发送已接受的报头,而不是星号(如错误所示,第一个X-Requested-With)。

更新:

*现在接受的是Access-Control-Allow-Headers。

根据MDN Web Docs 2021:

值*仅作为没有凭据的请求(没有HTTP cookie或HTTP身份验证信息的请求)的特殊通配符值。在带有凭据的请求中,它被视为没有特殊语义的字面头名称*。注意,Authorization标头不能是通配符,总是需要显式地列出。

我只是设法让dropzone和其他插件与此修复工作(angularjs + php后端)

 header('Access-Control-Allow-Origin: *'); 
    header("Access-Control-Allow-Credentials: true");
    header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
    header('Access-Control-Max-Age: 1000');
    header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token , Authorization');

将此添加到您的upload.php或发送请求的地方(例如,如果您有upload.html,您需要将文件附加到upload.php,然后复制并粘贴这4行)。 此外,如果你在chrome/mozilla中使用CORS插件/插件,请确保切换它们不止一次,以便启用CORS

这应该可以

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");

在.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