MUHAMMAD Siyab
MUHAMMAD Siyab

Reputation: 446

Unable to send POST data using fetch: React

I'm trying to send POST data to the PHP script on a different origin using javascript fetch API in react. I've got a CORS policy error as can be seen below:

enter image description here

In order to solve the above problem, i added these two lines to my PHP script:

header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');

But i'm still unable to get my problem solved. The POST data is not being sent.

JS code:

fetch('http://localhost/articles-mania/publish.php', {
    method: 'POST',
    body: data,  // JSON Object 
    headers : { 
        'Content-Type': 'application/json'
    }
})
.then((res) => res.json())
.then((response) => {
    this.setState({
      responseMsg: response.msg
    })
})

PHP Script:

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');

$title = $_POST['article_title'];
echo json_encode(array('msg' => $title));

Any idea?

Upvotes: 1

Views: 2979

Answers (2)

stackdog
stackdog

Reputation: 23

I just came across a similar issue where it seemed like I had all my CORS settings properly in place. What worked for me was adding a JSON.stringify() to the object you're passing into the body parameter.

E.g.

fetch('http://localhost/articles-mania/publish.php', {
    method: 'POST',
    body: JSON.stringify(data),  // JSON Object 
    headers : { 
        'Content-Type': 'application/json'
    }
})
.then((res) => res.json())
.then((response) => {
    this.setState({
      responseMsg: response.msg
    })
})

Upvotes: 1

Simon K
Simon K

Reputation: 1523

Perhaps try allowing the OPTIONS method as that is used to perform the pre-flight request...

Change this:

header('Access-Control-Allow-Methods: GET, POST, PUT');

To This:

header('Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS');

Upvotes: 1

Related Questions