如果我运行 curllocalhost:4000/myserver
,我会得到:{error: "foo"}
//MyAPI
function create(){
return httpPost('localhost:4000/myserver', myParams);
}
并调用它:
return MyApi.create(config, params).then(res => {
console.log("Full success" + JSON.stringify(res));
})
.catch(err => {
console.log("Full error" + JSON.stringify(err));
})
控制台日志仅显示Full error{"response":{}}
,这与我的cURL不匹配。
如何获取完整的错误和响应正文?
当你使用异步调用时,在大多数情况下(如果你的框架没有自动执行(,你必须解析响应以获取你可以进一步处理的数据,为此使用JSON.parse()
。
下面是实际发生的情况的示例(如果您从 Web 服务器接收数据,则数据始终是字符串类型(:
// Fake response
const response = '{ "name":"John", "age":30, "city":"New York"}';
console.log('typeof response:', typeof response);
// Parsing the response
const parsed = JSON.parse(response);
console.log('typeof parsed:', typeof parsed);
console.log('parsed:', parsed);