Javascript 将本机POST数据反应到API不工作

Javascript 将本机POST数据反应到API不工作,javascript,php,reactjs,react-native,Javascript,Php,Reactjs,React Native,当我在React Native中使用FormData将数据发布到php API时,我得到了注意:未定义索引响应。但是当我在php文件中硬编码参数时,我能够得到结果 我试过使用React文档中的JSON.stringify。我也有同样的问题。 在服务器端,我尝试了建议的文件获取内容('php://input“)它只返回null var data = new FormData(); data.append({ latitude: '55555', longitude: '99

当我在React Native中使用FormData将数据发布到php API时,我得到了
注意:未定义索引
响应。但是当我在php文件中硬编码参数时,我能够得到结果

我试过使用React文档中的
JSON.stringify
。我也有同样的问题。 在服务器端,我尝试了建议的
文件获取内容('php://input“)
它只返回null

  var data = new FormData();
  data.append({
    latitude: '55555',
    longitude: '9999',
  });

fetch('http://localhost/someapi', {
    method:'POST',
    headers:{
        'Accept':'application/json',
        'Content-Type': 'multipart/form-data',
        'Content-length': data.length
    },
    body: data
    })
    .then((response)=>response.text())
    .then((response)=>{
        console.log('  Show response');
        console.log(response);
    })
    .catch((err)=>{
        console.warn(err);
    });

我正在使用
response.text()
以便显示错误。否则
response.json()
会给我
意外的标记您正在传递
'multipart/form data'
头,因此您必须将
formdata
传递给body,而不是
json.stringify

 var formData = new FormData();
 formData.append('latitude', 55555);
 formData.append('longitude', 9999);

fetch('http://localhost/someapi', {
    method:'POST',
    headers:{
        'Accept':'application/json',
        'Content-Type': 'multipart/form-data'
    },
    body: formData
    })
    .then((response)=>{
        console.log('Response ==>',response);
    })
    .catch((err)=>{
        console.warn(err);
    });

只需在
Fetch
API中省略header对象就可以了


 headers:{
        'Accept':'application/json',
        'Content-Type': 'multipart/form-data'
    }
解决方案应该是这样的


fetch('http://localhost/someapi', {
    method:'POST',
    body: data
    })
    .then((response)=>response.text())
    .then((response)=>{
        console.log('  Show response');
        console.log(response);
    })
    .catch((err)=>{
        console.warn(err);
    });


如果您要发布JSON,那么假设您正在发布JSON:
'Content-Type':'application/JSON',
'Content-length':data.length
–并计算JSON字符串的长度,而不是数据对象的长度(
未定义的
)。console.log(响应)检查详细信息。或者您可以尝试使用axios而不是fetch,这样错误处理就很容易了。@Quentin-我在使用
body:json.stringify
时也尝试了
Content-Type':“application/json
。这并没有解决我的问题。@MaheshK。我已经在代码上安装了
console.log()
,用于调试。你能分享更多关于axios的信息吗?谢谢你的关注。它实际上不适用于
formData
。我多次修改代码,所以出错了。php似乎无法接收formData..使用$\u POST或$\u GET。

 headers:{
        'Accept':'application/json',
        'Content-Type': 'multipart/form-data'
    }

fetch('http://localhost/someapi', {
    method:'POST',
    body: data
    })
    .then((response)=>response.text())
    .then((response)=>{
        console.log('  Show response');
        console.log(response);
    })
    .catch((err)=>{
        console.warn(err);
    });