【问题标题】:Axios.get not returning any dataAxios.get 不返回任何数据
【发布时间】:2021-12-13 04:38:28
【问题描述】:

我无法在我的 API 上获得正确的信息。 我试过了,什么都没有回来

  const res = () => {
    axios.get('https://api.scripture.api.bible/v1/bibles', {
      headers: {
        'api-key': '5b5d4503884b7a2515e8cee8f4b00746',
      },
      
    })
  }

【问题讨论】:

  • get 返回一个承诺,因此您需要添加.then 并在那里处理响应,或者使用await(使用您的函数制作async

标签: reactjs api axios header


【解决方案1】:

您的代码工作正常,但您没有对响应做任何事情。 axios.get() 返回一个Promise,所以你需要使用.then()来处理它

const res = () => {
   axios.get("https://api.scripture.api.bible/v1/bibles", {
      headers: {
         "api-key": "5b5d4503884b7a2515e8cee8f4b00746"
      }
   })
   .then(function (response) {
      console.log(response);
   })
   .catch(function (error) {
      console.log(error);
   });
};

res();

或创建一个async 函数并使用async await

const res = async () => {
   try {
      const response = await axios.get("https://api.scripture.api.bible/v1/bibles", {
         headers: {
            "api-key": "5b5d4503884b7a2515e8cee8f4b00746"
         }
      });
      console.log(response);
   } catch (error) {
      console.log(error);
   }
};

res();

除了console.logging,你可以做任何事情,例如使用callback function

const res = async (callback, errorCallback) => {
   try {
      const response = await axios.get("https://api.scripture.api.bible/v1/bibles", {
         headers: {
            "api-key": "5b5d4503884b7a2515e8cee8f4b00746"
         }
      });
      callback(response);
   } catch (error) {
      errorCallback(error);
   }
};

const onSuccess = result => {
   const data = JSON.stringify(result);
   alert(data)
};

const onError = error => {
   alert(`Ops! An error occured: ${error}`);
};

res(onSuccess, onError);

【讨论】:

    猜你喜欢
    • 2020-02-15
    • 2020-04-11
    • 2019-02-10
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 2017-11-23
    • 2016-12-06
    • 2011-04-04
    相关资源
    最近更新 更多