【发布时间】:2020-05-27 10:04:05
【问题描述】:
当我发出 POST 请求时,我得到了错误
Access to XMLHttpRequest at 'http://localhost/vla-php/room/create.php' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
在控制台上。
使用 Postman 可以正常工作,但是,尝试从 React 前端使用它会导致上述错误。
我已经通过将访问控制设置为允许所有来源 (*) 启用了 CORS
.htaccess 是一个空文件。我怀疑这是否会成为障碍。
PHP 代码如下所示;
<?php
// required headers
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// get database connection
include_once '../config/database.php';
// instantiate product object
include_once '../objects/room.php';
$database = new Database();
$db = $database->getConnection();
$room = new Room($db);
// get posted data
$data = json_decode(file_get_contents("php://input"));
// make sure data is not empty
if(
!empty($data->name) &&
!empty($data->category) &&
!empty($data->type)
){
// set product property values
$room->name = $data->name;
$room->category = $data->category;
$room->type = $data->type;
// create the product
if($room->create()){
// set response code - 201 created
http_response_code(201);
// tell the user
echo json_encode(array("message" => "Room was created."));
}
// if unable to create the product, tell the user
else{
// set response code - 503 service unavailable
http_response_code(503);
// tell the user
echo json_encode(array("message" => "Unable to create room."));
}
}
// tell the user data is incomplete
else{
// set response code - 400 bad request
http_response_code(400);
// tell the user
echo json_encode(array("message" => "Unable to create room. Data is incomplete."));
}
?>
【问题讨论】:
-
您的后端是否正确响应preflight requests?