简体   繁体   English

如何使用 node-fetch 从 API 获取数据和响应状态?

[英]How to get data and response status from API using node-fetch?

As per the node-fetch documentation node-fetch根据 node-fetch 文档node-fetch

we can get the response status like this我们可以得到这样的响应状态

fetch('https://github.com/')
    .then(res => {
        console.log(res.status);
    });

and for getting the data和获取数据

fetch('https://api.github.com/users/github')
    .then(res => res.json())
    .then(jsonData => console.log(jsonData));

I have a scenario where I need to return the JSON data and the status from the response.我有一个场景,我需要从响应中返回 JSON 数据和状态。 I tried to use like this我试着像这样使用

     fetch('https://api.github.com/users/github')
            .then(res => res.json())
            .then(jsonData => {
             console.log(jsonData);
             console.log(jsonData.status);
      });

but the但是

console.log(jsonData.status)控制台.log(jsonData.status)

won't return the status.不会返回状态。 How I can get status and output data我如何获取状态和输出数据

The easiest solution would be to declare a variable and assign res.status value to it:最简单的解决方案是声明一个变量并为其分配res.status值:

let status; 
fetch('https://api.github.com/users/github')
  .then((res) => { 
    status = res.status; 
    return res.json() 
  })
  .then((jsonData) => {
    console.log(jsonData);
    console.log(status);
  })
  .catch((err) => {
    // handle error
    console.error(err);
  });

You can also try it that way using async/await :您也可以使用async/await这种方式尝试:

retrieveStatus = async (url) => {
  try {
    const response = await fetch(url);
    const { status } = response; 
    return status;
  } catch (err) {
   // handle error
    console.error(err);
  }
}

Then You can use it with any URL You want to:然后您可以将它与您想要的任何 URL 一起使用:

retrieveStatus('https://api.github.com/users/github')

Another alternative solution is using Promise.all另一种替代解决方案是使用Promise.all

fetch('https://api.github.com/users/github')
  .then(res => Promise.all([res.status, res.json()]))
  .then(([status, jsonData]) => {
    console.log(jsonData);
    console.log(status);
  });

Hope it helps希望能帮助到你

I might be going in opposite direction however I would suggest you to use requestJs , as its community is much bigger then node-fetch and provides lots of functionality.我可能会朝着相反的方向前进,但是我建议您使用requestJs ,因为它的社区比 node-fetch 大得多,并且提供了很多功能。

With requestJs you can fetch statusCode like使用 requestJs,您可以获取 statusCode 之类的

 request("https://api.github.com/users/github", (err, res, body) => {
     let statusCode = res.statusCode;
 });

RequestJs also provides lots of easy way to call different API methods and also easy to watch API request and API response. RequestJs 还提供了很多简单的方式来调用不同的 API 方法,也很容易观察 API 请求和 API 响应。

Here is yet another variant, using async lambda functions and array destructuring:这是另一个变体,使用异步 lambda 函数和数组解构:

fetch('https://api.github.com/users/github')
  .then(async (res) => {  
    return [await res.json(), res.status];
  })
  .then(([jsonData, status]) => {
    console.log(jsonData);
    console.log(status);
  })
  .catch((err) => {
    // handle error
    console.error(err);
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM