Fetch api - getting json body in both then and catch blocks for separate status codes

前端 未结 2 1814
你的背包
你的背包 2021-01-15 15:35

I am using fetch api for fetching an URL that might return:

Response : status = 200, json body = {\'user\': \'abc\', \'id\': 1}

相关标签:
2条回答
  • 2021-01-15 15:45

    Here's slightly different approach: With a one-liner I create a response-like promise with ok, status and json-as-object (not a promise), then I decide what to do with this object. Generally I reject with response if response.ok is false, otherwise I resolve with only the json-data. Network errors/json-parse-errors are rejected as usual.

    fetch(url, options)
        .then(r => r.json().then(json => ({ok: r.ok, status: r.status, json})))
        .then( r => r.ok ? r.json: Promise.reject(r))
    
    0 讨论(0)
  • 2021-01-15 15:52

    response.json() returns an asynchronous result. You are not returning the object at parseJSON from within .then() chained to response.json(). To correct that issue you can return response.json() promise at parseJSON call and return object containing data and status from within .then() chained to response.json()

    function parseJSON(response) {
        return response.json().then(json => {
              return {
                       data: json,
                       status: response.status  
                     }
        })         
    }  
    
    0 讨论(0)
提交回复
热议问题