简体   繁体   中英

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:

在此处输入图片说明

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?

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');

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.

Eg

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
    })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM