相关疑难解决方法(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万
查看次数

获取api - 在两者中获取json body并捕获块以获取单独的状态代码

我使用fetch api来获取可能返回的URL:

回复:状态= 200,json body = {'user':'abc','id':1}

要么

回复:状态= 400,json body = {'reason':'某些原因'}

要么

回复:状态= 400,json body = {'reason':'其他原因'}

我想创建一个单独的函数request(),我从代码的各个部分使用如下:

    request('http://api.example.com/').then(
        // status 200 comes here
        data => // do something with data.id, data.user
    ).catch(
        // status 400, 500 comes here
        error =>  // here error.reason will give me further info, i also want to know whether status was 400 or 500 etc
    )
Run Code Online (Sandbox Code Playgroud)

我无法进行200到400,500之间的分割(我试过抛出一个错误).当我抛出错误时,我发现很难仍然提取JSON主体(用于error.reason).

我目前的代码如下:

import 'whatwg-fetch';

/**
 * Requests a URL, returning a promise
 */
export …
Run Code Online (Sandbox Code Playgroud)

javascript promise es6-promise fetch-api

1
推荐指数
1
解决办法
4870
查看次数

标签 统计

es6-promise ×2

fetch-api ×2

javascript ×2

promise ×2