如果我运行 curl localhost:4000/myserver
,我得到:
{错误:“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()
为此。
下面是真实情况的示例(如果您从网络服务器接收数据,数据始终是字符串类型):
// 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);
关于javascript - 使用 httpPost 的 422 响应返回 {"response":{}} instead of the actual API response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52616066/