无法使用提取发送POST数据:React

时间:2018-07-10 11:08:29

标签: javascript php cors fetch

我正在尝试使用javascript fetch API在不同的origin上将POST数据发送到PHP脚本。我有一个CORS政策错误,如下所示:

enter image description here

为了解决上述问题,我在我的PHP脚本中添加了以下两行:

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

但是我仍然无法解决我的问题。 POST数据未发送。

JS代码:

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脚本:

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

有什么主意吗?

2 个答案:

答案 0 :(得分:1)

也许尝试允许使用$ cat tst.awk NF { tag = val = $0 sub(/:.*/,"",tag) sub(/[^:]*:[[:space:]]*/,"",val) tag2val[tag] = val tags[++numTags] = tag next } { prt() } END { prt() } function prt( tagNr,tag,val) { OFS="," if ( ++numRecs == 1 ) { for (tagNr=1; tagNr<=numTags; tagNr++) { tag = tags[tagNr] printf "\"%s\"%s", tag, (tagNr<numTags ? OFS : ORS) } } for (tagNr=1; tagNr<=numTags; tagNr++) { tag = tags[tagNr] val = tag2val[tag] gsub(/"/,"\"\"",val) printf "\"%s\"%s", val, (tagNr<numTags ? OFS : ORS) } delete tag2val numTags = 0 } $ awk -f tst.awk file "dn","objectClass","cn","uid","creationTime","uidNumber" "uid=asd,ou=People,dc=MY,dc=ORG","...","Adam Saddler","asd","20110409131545-0700","1234" "uid=mfwth,ou=People,dc=MY,dc=ORG","...","Mike Foksworth","mfwth","20160704144535-0800","12345" 方法来执行飞行前请求...

更改此:

OPTIONS

为此:

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

答案 1 :(得分:1)

我刚遇到一个类似的问题,好像我所有的CORS设置都正确到位。对我有用的是在要传递给body参数的对象中添加一个JSON.stringify()。

例如

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
    })
})
相关问题