【发布时间】:2019-11-09 21:11:21
【问题描述】:
我正在使用 fetch() 从 API 获取一些数据。在 Postman 中测试时,数据作为 JSON 成功返回。但是,当在 android 上从 react 本机应用程序进行测试时,我得到一个 text/html 响应,不知道为什么。如何从 console.log() 中的文本查看响应正文以进行调试?当我执行 console.log(resp) 时,我看不到身体。
const response = await fetch('https://web.com/api/usersignup', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then(resp => {
this.setState({spinner: false});
console.log(resp);// output in console is pasted under this code
return resp.text();
//return resp.json();
})
.then((responseJson) => {
console.log(responseJson);
})
.catch(error => {
this.setState({spinner: false});
Alert.alert('Error', error.message);
throw error;
});
我在使用 console.log() 时在 Metro Builder 中得到的输出。不包括正文。
Response {
"_bodyBlob": Blob {
"_data": Object {
"blobId": "63acc7d8-bd8a-4dd7-b33b-f0e4f202f97e",
"offset": 0,
"size": 0,
},
},
"_bodyInit": Blob {
"_data": Object {
"blobId": "63acc7d8-bd8a-4dd7-b33b-f0e4f202f97e",
"offset": 0,
"size": 0,
},
},
"headers": Headers {
"map": Object {
"cache-control": "public, max-age=0",
"connection": "keep-alive",
"content-length": "0",
"content-type": "text/html; charset=UTF-8",
"date": "Sat, 09 Nov 2019 21:06:05 GMT",
"server": "Apache",
"x-ratelimit-limit": "60",
"x-ratelimit-remaining": "59",
},
},
"ok": true,
"status": 200,
"statusText": undefined,
"type": "default",
"url": "https://web.com/api/usersignup",
}
【问题讨论】:
-
你试过axios吗?对http请求很有帮助,提供了更好的响应对象。
-
同样的问题,如何在控制台中实际输出正文?使用 POST 发送到服务器的数据存在一些问题,我需要从 API/服务器获取完整的调试响应,我该怎么做?
-
对于 axios,这是响应模式:{ data: {}, status: 200, statusText: 'OK', headers: {}, config: {}, request: {} }
-
如果你没有得到数据密钥,这是你的api造成的,也许你应该用像Postman这样的API测试工具来调试。
标签: react-native expo