Don*_*eph 0 javascript fetch node.js node-fetch
根据node-fetch文档node-fetch
我们可以得到这样的响应状态
fetch('https://github.com/')
.then(res => {
console.log(res.status);
});
Run Code Online (Sandbox Code Playgroud)
并获取数据
fetch('https://api.github.com/users/github')
.then(res => res.json())
.then(jsonData => console.log(jsonData));
Run Code Online (Sandbox Code Playgroud)
我有一个场景,我需要从响应中返回JSON数据和状态.我试着这样用
fetch('https://api.github.com/users/github')
.then(res => res.json())
.then(jsonData => {
console.log(jsonData);
console.log(jsonData.status);
});
Run Code Online (Sandbox Code Playgroud)
但是
执行console.log(jsonData.status)
不会返回状态.我如何获得状态和输出数据
最简单的解决方案是声明一个变量并为其分配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);
});
Run Code Online (Sandbox Code Playgroud)
您也可以使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后你可以使用任何你想要的网址:
retrieveStatus('https://api.github.com/users/github')
另一种替代解决方案是使用 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);
});
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你
归档时间: |
|
查看次数: |
10171 次 |
最近记录: |