【发布时间】:2021-03-20 21:55:20
【问题描述】:
概述
我的 react 应用 托管在 githup-pages 上,而 PHP API 托管在标准的付费托管上。
这有效 (GET)
当我开始开发我的应用程序时,我遇到了一个非常流行的错误,即Access to fetch at ... has been blocked by CORS policy。我找到了一个快速修复方法,即在 PHP 的第一行中写下这个 header("Access-Control-Allow-Origin: *"),它工作。然而,那些是 GET 请求。
这不起作用(POST)
这次我有一段代码,我必须在其中使用 POST 请求并需要访问它的响应。这是负责发送 post 请求的代码:
const editEvent = async () => {
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json', },
body: JSON.stringify({ eventID: chosenEvent, courseID: courseID, groupID: groupID, time:time, date: date, description: description, typeID: typeID, password: password}),
mode: 'cors',
};
const response = await fetch(`https://aleksanderblaszkiewicz.pl/kiedykolos/edit_event.php`, requestOptions);
}
又发生了 - 我收到同样的错误 Access to fetch at ... has been blocked by CORS policy。我现在使用的解决方案是使用mode: 'no cors',但它不让我得到响应,因为它是不透明的。我发现的另一个解决方案是添加更多标题:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Accept, Authorization, X-Requested-With, X-Auth-Token, Origin, Application");
但它也不起作用。有什么建议吗?完整的错误代码:
CORS 策略已阻止访问来自源“http://localhost:3000”的“https://aleksanderblaszkiewicz.pl/kiedykolos/add_event.php”获取:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。
完整的php代码:
header("Access-Control-Allow-Origin: http://localhost:3000");
header("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Accept, Authorization, X-Requested-With, X-Auth-Token, Origin, Application");
$servername = "...";
$username = "...";
$password = "...";
$dbname = "...";
$connection = new mysqli($servername, $username, $password, $dbname);
mysqli_set_charset($connection, 'utf8');
if ($connection -> connect_errno) {
echo "Failed to connect to MySQL: " . $connection -> connect_error;
exit();
}
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);
$courseID = $input["courseID"];
$groupID = $input["groupID"];
$date = $input["date"];
$time = $input["time"];
$description = $input["description"];
$typeID = $input["typeID"];
$password = $input["password"];
$sql = "INSERT
INTO `events` (`id`, `date`, `time`, `description`, `course_fk`, `year_group_fk`, `type_fk`)
VALUES (NULL, '$date', '$time', '$description', '$courseID', '$groupID', '$typeID')";
if($password == "Ujebale321!") {
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
echo "Success";
}
else {
echo "Wrong password";
}
mysqli_close($connection);
?>
【问题讨论】:
-
评论不用于扩展讨论;这个对话是moved to chat。