首页 > 解决方案 > response.json 未定义 express.js

问题描述

所以这是我现在的代码:

    function geoPerformAction(e) {
  getGeoApiData(document.getElementById('zipPostCode').value)
    .then((APIarr) => {
      postGeoData('/geoadd', { Lat: APIarr[0] });
    })
    .then(function () {
      updateUIGeo();
    })
}

//Friend helped with me with get API data
/* Function to GET Web API Data*/
const getGeoApiData = async ( place) => {
  const response = await fetch("https://pokeapi.co/api/v2/pokemon/" + place + "/");
  try {
    const webData =  response.json();

    const Pla = webData;
    console.log(Pla);


const APIarr = [Pla];

    return APIarr;
  }
  catch (error) {
    console.log("error", error);
  }
}

每次我使用它时,webdata 变量都是未定义的。为什么会这样?为什么不返回我请求的数据?

谢谢你。

标签: javascriptnode.jsexpressundefinedbackend

解决方案


你不是在等待第二个承诺得到解决

const webData =  await response.json();

例子:

async function fetchAsync () {
  // await response of fetch call
  const response = await fetch('https://api.github.com');
  // only proceed once promise is resolved
  const data = await response.json();
  // only proceed once second promise is resolved
  return data;
}

推荐阅读