Javascript 将本机POST数据反应到API不工作
当我在React Native中使用FormData将数据发布到php 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
注意:未定义索引响应。但是当我在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);
});