首页 > 解决方案 > 如何使用 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.dataconsole.log它会返回我的响应undefined ,如果它可以提供帮助,这是我尝试使用时得到的控制台中的响应response.json()

在此处输入图像描述

标签: javascriptspring-boot

解决方案


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);
}

推荐阅读