首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >获取response.json()和response.status

获取response.json()和response.status
EN

Stack Overflow用户
提问于 2017-11-13 14:57:00
回答 5查看 73.9K关注 0票数 50

这是使用body.json()并获取状态代码的唯一方法吗?

代码语言:javascript
复制
let status;

return fetch(url)
    .then((response => {
         status = response.status;
         return response.json()
     })
    .then(response => {
        return {
            response: response,
            status: status
        }
    });

这不起作用,因为它返回响应字段中的承诺:

代码语言:javascript
复制
.then((response)=> {return {response: response.json(), status: response.status}})
EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2017-11-13 15:01:11

您的状态在第二个then中不可见。您可以在单个then中获得这两个属性。

json()向您返回一个新的承诺,因此您需要在该函数的结果的then中创建对象。如果你从一个函数中返回一个承诺,它将被实现,并将返回实现的结果--在我们的例子中是对象。

代码语言:javascript
复制
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(r =>  r.json().then(data => ({status: r.status, body: data})))
.then(obj => console.log(obj));

票数 114
EN

Stack Overflow用户

发布于 2017-11-13 15:16:04

上周我也遇到了同样的问题。.json方法向解析的JSON返回一个承诺,而不是解析的JSON本身。如果希望同时访问响应和解析的JSON,则需要使用以下嵌套闭包:

代码语言:javascript
复制
fetch(url)
    .then(response => {
        response.json().then(parsedJson => {
            // code that can access both here
        })
    });

或者,您可以使用async/await语法:

代码语言:javascript
复制
async function fetchTheThing() {
    const response = await fetch(url);
    const parsedJson = await response.json();

    // code that can access both here
}

当然,您需要检查错误,无论是使用.catch(...)调用还是使用带有async函数的try...catch块。您可以创建一个处理JSON和错误案例的函数,然后将其用于所有获取。例如,如下所示:

代码语言:javascript
复制
function fetchHandler(response) {
    if (response.ok) {
        return response.json().then(json => {
            // the status was ok and there is a json body
            return Promise.resolve({json: json, response: response});
        }).catch(err => {
            // the status was ok but there is no json body
            return Promise.resolve({response: response});
        });

    } else {
        return response.json().catch(err => {
            // the status was not ok and there is no json body
            throw new Error(response.statusText);
        }).then(json => {
            // the status was not ok but there is a json body
            throw new Error(json.error.message); // example error message returned by a REST API
        });
    }
}

我不认为这是最好的设计模式,但希望这澄清了fetch是如何工作的。

票数 26
EN

Stack Overflow用户

发布于 2020-09-19 17:57:45

对我来说,使用两种方法似乎是不必要的。

异步/等待可以很容易地完成任务。

代码语言:javascript
复制
    fetch('http://test.com/getData')
      .then( async (response) => {

        // get json response here
        let data = await response.json();
        
        if(data.status === 200){
         // Process data here
        }else{
         // Rest of status codes (400,500,303), can be handled here appropriately
        }

      })
      .catch((err) => {
          console.log(err);
      })
票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47267221

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档