为什么我得到XMLHttpRequest无法加载 - 预检响应不成功只有Delete方法错误?

时间:2018-02-13 16:43:23

标签: php angular cors angular-http

PHP资源文件:

<FileInput
    label="File input"
    multiple={true}
>
    <FileField source="rawFile.preview" title="rawFile.name" target="_blank"/>
</FileInput>

Angular服务文件:

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST, DELETE, OPTIONS, GET, PUT");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

require_once ("center_service.php");

$data = json_decode(file_get_contents("php://input"));
$method = $_SERVER['REQUEST_METHOD'];

if (!isset($routes[2])) {
    $sql = "SELECT * FROM centers;";
    Center::readCenter($sql);
} else if (isset($routes[2]) && is_numeric($routes[2]) && $method === "GET") {
    $sql = "SELECT * FROM centers WHERE id='$routes[2]';";
    Center::readCenter($sql);
} else if (isset($routes[2]) && is_numeric($routes[2]) && $method === "DELETE") {
    Center::deleteCenter($routes[2]);
}
else {
    header('HTTP/1.0 404 Not Found');
    require '404.php';
}

get方法正在运行并返回结果,但它不适用于delete方法。如果是因为CORS,那么为什么get方法有效?

控制台日志: enter image description here

网络: enter image description here

相关问题:

“XMLHttpRequest cannot load file:///… Preflight response is not successful” error

Preflight response is not successful

Express server and Axios CORS Preflight response is not successful

1 个答案:

答案 0 :(得分:0)

好吧,我认为这是因为如果方法与GET或DELETE不同,则返回404.因此,当处理预检请求(动词OPTIONS)时,返回404.

这是PHP中的CORS示例(here

主要话题是:

  

这里重要的一点是,API脚本需要识别何时收到初始OPTIONS请求,并在这种情况下返回相应的访问控制头(仅此而已)。然后,浏览器启动第二个请求,其中完成了实际工作。

在您的具体情况下,我认为代码应为:

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    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;
}

如果您想要更全面地启用cors,您只需添加

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

在你的php脚本(see here