javascript - 如何使用 fetch 函数 javascript 获取 API 响应数据?
问题描述
我想获取我的 API 响应数据,我在 javascript 中使用 fetch 函数,但我没有在响应中获取数据字段,尽管我的 API 在一切正常时返回响应。此外,当我调用 API 时,我的200
响应状态证明请求工作正常,这里是我用来调用 API 的代码和从 API 获得的响应的屏幕截图:
`function getAuthToken(){
fetch("http://localhost:8080/authenticate",{
method:"POST", headers:{'Accept':'Application/json; charset=utf-8',
'Content-Type':'Application/json; charset=utf-8',
'Access-Control-Allow-Origin':'*'
},
body:JSON.stringify(credentials)
}).then((response)=>{
console.log("ramses");
console.log(response.json().jwttoken);
//console.log(JSON.parse(response.statusText).jwttoken);
if(response.status==200){
fetch("http://localhost:8080/user/add",{
method:"POST",
headers:{
'Accept':'Application/json; charset=utf-8',
'Content-Type':'Application/json; charset=utf-8',
'Access-Control-Allow-Origin':'*',
'Authorization':'Bearer'+a
},
body:JSON.stringify(data),
}).then(response => alert(JSON.stringify(response))).catch(error => alert("Erreur : " + error));
}
});
}`
最后,当我尝试使用 in 它获取响应时response.data
,console.log
它会返回我的响应undefined
,如果它可以提供帮助,这是我尝试使用时得到的控制台中的响应response.json()
解决方案
fetch 函数是一个返回响应的 Promise。在您等待获得此响应后,调用 .json() 方法,该方法也返回一个 Promise。这就是为什么你需要做 2.then()。
fetch('yoururl')
.then((response) => response.json())
.then((data) => console.log(data));
或者您可以在异步函数中使用 async-await 调用 fetch 函数:
async function getData(){
let response = await fetch('yoururl');
let data = await response.json();
console.log(data);
}
推荐阅读
- c# - 常见的 Asp.Net Core 系统绘图错误
- ios - 为什么我不能在选择器视图列表中选择我的第一个数据?
- sql - 如何在更新查询中使用 SUBSTR
- android - 底部应用栏导航图标不是垂直居中
- python - 使用 python + sqlanydb 在 SAP IQ 上加载数据。'由于文件权限,文件操作失败
- apache - 为 Magento 在 Plesk(apache2、nginx 和 FPM)上设置 Varnish
- django - 在 home.html 中链接静态文件
- apache-spark - SecurityManager:禁用身份验证;ui acls 禁用;具有查看权限的用户:
- asp.net - Object Required 424 错误只发生在 IE11
- c# - 按名称动态获取常量的嵌套值