I have already done several searches concerning my problem but I cannot find precisely how to do it.
I use axios and a method post when I try to use my function it does not work I use react in front and php in back end
Here is my error code
has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
my code 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"]);
}
My code react :
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);
});
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…