If I don't use Headers and POST fields, the current request successfully handling. But, If I try send POST fields and use the Content-Type: application/json header.
That doesn't work.
I getting the CORS Error when use that. How can I solve that?
My codes:
page.js (The currently codes here)
import React from 'react';
import ReactDOM from 'react-dom';
// Components :: Layouts
import Header from '../layouts/header.js';
import Footer from '../layouts/footer.js';
// Components :: HTML Component
import Loading from '../assets/img/loading.svg';
class Page extends React.Component
{
constructor(props)
{
super(props);
this.loadPage = this.loadPage.bind(this);
this.state = {
content: null,
loading: 'loadingArea'
}
}
loadPage(page_slug)
{
var data = {
slug: "hello",
}
var postData = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
};
fetch('http://localhost', postData)
.then((response) => response.json())
.then((responseJson) =>
{
this.setState({
content: responseJson,
loading: 'loadingArea d-none',
});
})
.catch((error) =>
{
console.error(error);
});
}
render()
{
const page_slug = this.props.match.params.page;
this.loadPage(page_slug);
return (
<div className="index">
<Header/>
<div className={this.state.loading}>
<img src={Loading}/>
</div>
{this.state.content}
<Footer/>
</div>
);
}
}
export default Page;
And the PHP API file (requested file):
<?php
header('Content-Type: application/json');
ob_start();
print_r($_POST);
$e = ob_get_clean();
echo json_encode([$e]);