相关疑难解决方法(0)

fetch:使用JSON错误对象拒绝承诺

我有一个HTTP API,它在成功和失败时返回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"
}
Run Code Online (Sandbox Code Playgroud)

我想在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()); …
Run Code Online (Sandbox Code Playgroud)

javascript promise es6-promise fetch-api

56
推荐指数
3
解决办法
5万
查看次数

标签 统计

es6-promise ×1

fetch-api ×1

javascript ×1

promise ×1