在 response.json() 之后获取 http 响应状态码

Get http response status code after response.json()

我想在 response.json 之后获取 http 状态代码以便稍后在我的逻辑中使用它,我可以用它做些什么吗?

function apiRequest(path, options) {
    fetch("api/" + path, options)
        .then(response => response.json())
        .then(data => {
            let res = {
                code: 200 //I want to put http status code here,
                data: data
            }

            return res;
        })
}

试试这个

function apiRequest(path, options) {
    fetch("api/" + path, options)
        .then(response => Promise.all([Promise.resolve(response.status), response.json()]))
        .then(([status, data]) => {
            let res = {
                code: status //I want to put http status code here,
                data: data
            }

            return res;
        })
}

这使用 then 有点棘手(正如您目前正在做的那样),因为您想直接从响应(这是一个承诺)中获取数据,并从解析的正文中获取更多数据(这是另一个承诺)。

因此您可以将状态和数据承诺包装在 Promise.all 和 return 中,从第一个开始:

const apiRequest = () => {
  const url = "//swapi.dev/api/planets/1/";
  fetch(url)
    .then((response) => Promise.all([response.status, response.json()]))
    .then(([status, data]) => console.log({status, data}))
}

... 但是使用 async/await 语法并放弃回调会更容易,然后您只需要担心单个函数(因此范围)而不是多个。

const apiRequest = async () => {
  const url = "//swapi.dev/api/planets/1/";
  const response = await fetch(url);
  const data = await response.json();
  const status = response.status;
  console.log({status, data})
}

作为替代方案,您可以考虑 async/await。这样您就可以更轻松地同时访问 responsedata

async function apiRequest(path, options) {
    const response = await fetch("api/" + path, options)
    const data = await response.json()

    let res = {
         code: response.status,
         data: data
    }

    // Do something with res
}

你可以先 git 然后再 return response.json 这样的事情

function apiRequest(path, options) {
  fetch("api/")
    .then((response) => {
      let status = response.status;
      console.log("status", status);
      return response.json();
    })
    .then((data) => {
      console.log(data);
    });
}
apiRequest();