根据节点获取文档节点取
我们可以得到这样的响应状态
fetch('https://github.com/')
    .then(res => {
        console.log(res.status);
    });以及为了获取数据
fetch('https://api.github.com/users/github')
    .then(res => res.json())
    .then(jsonData => console.log(jsonData));我有一个场景,需要从响应返回JSON数据和状态。我试着用这种方法
     fetch('https://api.github.com/users/github')
            .then(res => res.json())
            .then(jsonData => {
             console.log(jsonData);
             console.log(jsonData.status);
      });但是
console.log(jsonData.status)
不会返回状态的。如何获得状态和输出数据
发布于 2018-08-22 19:39:07
最简单的解决方案是声明一个变量并将res.status值赋值给它:
let status; 
fetch('https://api.github.com/users/github')
  .then((res) => { 
    status = res.status; 
    return res.json() 
  })
  .then((jsonResponse) => {
    console.log(jsonResponse);
    console.log(status);
  })
  .catch((err) => {
    // handle error
    console.error(err);
  });您也可以使用async/await尝试这种方法。
const retrieveResponseStatus = async (url) => {
  try {
    const response = await fetch(url);
    const { status } = response; 
    return status;
  } catch (err) {
   // handle error
    console.error(err);
  }
}然后您可以将它与您想要的任何URL一起使用:
const status = await retrieveStatus('https://api.github.com/users/github')
发布于 2018-08-22 19:54:25
另一种替代解决方案是使用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);
  });希望它能帮上忙
发布于 2018-08-22 20:05:42
不过,我建议您使用请求,因为它的社区要比节点获取大得多,并且提供了很多功能。
使用requestJs,您可以获取类似的statusCode
 request("https://api.github.com/users/github", (err, res, body) => {
     let statusCode = res.statusCode;
 });RequestJs还提供了许多简单的方法来调用不同的API方法,也可以很容易地查看API请求和API响应。
https://stackoverflow.com/questions/51973958
复制相似问题