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

前端 未结 2 1828
你的背包
你的背包 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))
    

提交回复
热议问题