我有一个HTTP API,在成功和失败时都返回JSON数据。提取:拒绝承诺与JSON错误对象
一个例子失败是这样的:
~ ◆ http get http://localhost:5000/api/isbn/2266202022
HTTP/1.1 400 BAD REQUEST
Content-Length: 171
Content-Type: application/json
Server: TornadoServer/4.0
{
"message": "There was an issue with at least some of the supplied values.",
"payload": {
"isbn": "Could not find match for ISBN."
},
"type": "validation"
}
我想在我的JavaScript代码来实现是这样的:
fetch(url)
.then((resp) => {
if (resp.status >= 200 && resp.status < 300) {
return resp.json();
} else {
// This does not work, since the Promise returned by `json()` is never fulfilled
return Promise.reject(resp.json());
}
})
.catch((error) => {
// Do something with the error object
}
你的意思是'json'方法返回一个'Promise'? – thefourtheye
是的,根据工作组的fetch规范:https://fetch.spec.whatwg.org/#concept-body-consume-body – jbaiter