I am trying to make a POST request from my React app (via Axios) to my API on the server-side written in PHP.
I already added these headers on the response side.
header( 'Access-Control-Allow-Origin: *' );
header( 'Access-Control-Allow-Methods: GET, POST, PUT, DELETE' );
header( 'Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, X-PINGHEADER' );
But the problem that I am currently facing right now is this,
and I know that it makes the POST request, but it blocks the post data being sent through it. I've read this from Mozilla, it says that only certain Content-Type is allowed through the CORS, but I need to send my data in application/json format.
I did change the request's Content-Type header to x-www-form-urlencoded and it does receive the data because it seems CORS don't block it. But when I changed it back to application/json, and it does not.
This is the request code from my React app.
import axios from 'axios';
const api = axios.create({
baseURL: CONST.API_URL,
params: {
key: process.env.REACT_APP_API_KEY
}
});
api.post('/create_user', { username: "johndoe" }).then(o => {
// something goes here..
const { data } = o;
console.log(data.message);
}).catch(e => console.error(e));
This is my sample response:
<?php
header( 'Access-Control-Allow-Origin: *' );
header( 'Access-Control-Allow-Methods: GET, POST, PUT, DELETE' );
header( 'Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, X-PINGHEADER' );
$username = $_POST['username'];
$response = array(
"message" => "Hello $username!",
);
echo json_encode($response);
exit;
?>
As you can see, the $username has blank value because the CORB thing blocked the post data.
I expect Hello johndoe!
from the code above: