javascript 如何使用 node-fetch 从 API 获取数据和响应状态?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/51973958/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get data and response status from API using node-fetch?
提问by Dony Joseph
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. I tried to use like this
我有一个场景,我需要从响应中返回 JSON 数据和状态。我试着像这样使用
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
不会返回状态。我如何获取状态和输出数据
回答by KarlR
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 for example
console.error(err);
});
You can also try it that way using async/await:
您也可以使用async/await以下方式尝试:
retrieveStatus = async (url) => {
try {
const res = await fetch(url);
const { status } = res;
return status;
} catch (err) {
// handle error for example
console.error(err);
}
}
Then You can use it with any url You want to:
然后您可以将它与您想要的任何网址一起使用:
retrieveStatus('https://api.github.com/users/github')
retrieveStatus('https://api.github.com/users/github')
回答by deerawan
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
希望能帮助到你
回答by NAVIN
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 响应。

