我正在与React Native一起学习, 但我无法正确回应 我的提取代码是:
try {
let response = fetch(
"http://192.168.1.106/little_api/index.php",
{
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}
);
console.log(response);
响应为:
尝试邮递员时从api获得的api响应:
答案 0 :(得分:2)
fetch()
函数返回一个诺言,因此您应使用以下两种方法之一来解决此诺言:
1 /使用.then()
fetch(
"http://192.168.1.106/little_api/index.php",
{
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}
).then(response => {
console.log(response); //<- your response here
}).catch(error => {
console.log(error); //<-catch error
});
2 /使用async/await
语法:您应在调用fetch的函数上添加async关键字
async getResponse(){
try {
let response = fetch(
"http://192.168.1.106/little_api/index.php",
{
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}
);
console.log(response); //<- your response here
} catch(e){
console.log(e);<-catch error
}
}
答案 1 :(得分:1)
您可以使用formdata发送它:
let formData = new FormData();
formData.append('firstname', 'test');
如果这样做,则不必使用JSON.stringify:
fetch(
"http://192.168.1.106/little_api/index.php",
{
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: data
}
...
答案 2 :(得分:0)
fetch
是一个异步方法,这意味着它需要一个.then
回调。立即从中获得的数据然后附加了一个json()
方法,以便以可读格式检索实际数据。
fetch("http://192.168.1.106/little_api/index.php", {
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
}).then(response => response.json())
.then(data => {
console.log(data) // this should return your data
})
.catch(err => console.log(err))
正如Mahdi N在回答中所说,您可以使用async/await
语法来检索数据,而无需嵌套的回调。