Javascript 带有 PHP 标头的跨域请求标头 (CORS)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8719276/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:12:14  来源:igfitidea点击:

Cross-Origin Request Headers(CORS) with PHP headers

phpjavascriptxmlhttprequestcors

提问by slashingweapon

I have a simple PHP script that I am attempting a cross-domain CORS request:

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

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

Yet I still get the error:

但我仍然收到错误:

Request header field X-Requested-Withis not allowed by Access-Control-Allow-Headers

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

Anything I'm missing?

我缺少什么吗?

采纳答案by KARASZI István

Access-Control-Allow-Headersdoes not allow *as accepted value, see the Mozilla Documentation here.

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

Instead of the asterisk, you should send the accepted headers (first X-Requested-Withas the error says).

您应该发送接受的标头而不是星号(首先X-Requested-With是错误所说的)。

回答by slashingweapon

Handling CORS requests properly is a tad more involved. Here is a function that will respond more fully (and properly).

正确处理 CORS 请求有点复杂。这是一个响应更充分(和正确)的函数。

/**
 *  An example CORS-compliant method.  It will allow any GET, POST, or OPTIONS requests from any
 *  origin.
 *
 *  In a production environment, you probably want to be more restrictive, but this gives you
 *  the general idea of what is involved.  For the nitty-gritty low-down, read:
 *
 *  - https://developer.mozilla.org/en/HTTP_access_control
 *  - http://www.w3.org/TR/cors/
 *
 */
function cors() {

    // Allow from any origin
    if (isset($_SERVER['HTTP_ORIGIN'])) {
        // Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
        // you want to allow, and if so:
        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    }

    // Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            // may also be using PUT, PATCH, HEAD etc
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

        exit(0);
    }

    echo "You have CORS!";
}

回答by Fiach Reid

I got the same error, and fixed it with the following PHP in my back-end script:

我遇到了同样的错误,并在我的后端脚本中使用以下 PHP 修复了它:

header('Access-Control-Allow-Origin: *');

header('Access-Control-Allow-Methods: GET, POST');

header("Access-Control-Allow-Headers: X-Requested-With");

回答by Csongor Halmai

Many description internet-wide don't mention that specifying Access-Control-Allow-Originis not enough. Here is a complete example that works for me:

互联网上的许多描述都没有提到指定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);

回答by Fedeco

I've simply managed to get dropzone and other plugin to work with this fix (angularjs + php backend)

我只是设法让 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');

add this in your upload.php or where you would send your request (for example if you have upload.html and you need to attach the files to upload.php, then copy and paste these 4 lines). Also if you're using CORS plugins/addons in chrome/mozilla be sure to toggle them more than one time,in order for CORS to be enabled

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

回答by Finn Johansen

If you want to create a CORS service from PHP, you can use this code as the first step in your file that handles the requests:

如果要从 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

回答by shades3002

CORS can become a headache, if we do not correctly understand its functioning. I use them in PHP and they work without problems. reference here

如果我们没有正确理解 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");

回答by Labib Hussain

This much code works down for me when using angular 4 as the client side and PHP as the server side.

当使用 angular 4 作为客户端和 PHP 作为服务器端时,这些代码对我来说很有效。

header("Access-Control-Allow-Origin: *");

回答by user8453321

this should work

这应该有效

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

回答by Rakyesh Kadadas

add this code in .htaccess

.htaccess 中添加此代码

add custom authentication key's in header like app_key,auth_key..etc

在标题中添加自定义身份验证密钥,如 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"