[英]how to fix the problem Axios : has been blocked by CORS policy:
我已經對我的問題進行了多次搜索,但我無法准確找到如何去做。
當我嘗試使用我的 function 時,我使用 axios 和一個方法帖子,它不起作用我在前面使用反應,在后端使用 php
這是我的錯誤代碼
has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
我的代碼 php:
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, Acces-Control-Allow-Headers, Authorization, X-Requested-With");
include('../../config/Database.php');
include('../../models/Post.php');
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$database = new Database();
$db = $database->connect();
$post = new Post($db);
$data = json_decode(file_get_contents("php://input"));
$post->title = $data->title;
$post->user_id = $data->user_id;
$post->categorie_id = $data->categorie_id;
$post->body = $data->body;
$post->author = $data->author;
if(!empty($post->title) && !empty($post->user_id) && !empty($post->categorie_id) && !empty($post->body) && !empty($post->author)) {
if($post->create_post()) {
http_response_code(200);
echo json_encode(["message" => "Post is created"]);
}else {
http_response_code(405);
echo json_encode(["message" => "Post is not created"]);
}
}else {
echo "pas ok";
}
}else {
http_response_code(405);
echo json_encode(["message" => "This method is not authorized"]);
}
我的代碼反應:
axios.post('http://localhost/web/api/post/write.php', {
"title": "create post",
"user_id": "5",
"categorie_id": "1",
"body": "create post",
"author": "author"
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
您可以運行 Chrome 禁用 Web 安全性(僅限本地測試)
在您的終端上:
open -n -a /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --args --user-data-dir="/tmp/chrome_dev_test" --disable-web-security
您可以創建一個單獨的快捷方式,使其永遠不會用於正常瀏覽,僅用於本地調試。
請按照以下步驟操作:
"[PATH_TO_CHROME]\chrome.exe" --disable-web-security --disable-gpu --user-data-dir=~/chromeTemp
注意:在 Windows 10 命令將是:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --disable-gpu --user-data-dir=~/chromeTemp
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.