简体   繁体   English

Axios 获取请求返回错误未定义

[英]Axios get request returns error UNDEFINED

I am trying to get the data from the certain API,I am getting an error:Undefined in the console.我正在尝试从某个 API 获取数据,但出现错误:控制台中未定义。

const getApiAndEmit =async socket => {
    try 
    {
        
     
      await axios.get('https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/findByDistrict?district_id=571&date=25-05-2021').then((response) =>
      {
         this.resp=response.data;
      }) ;
     
      //socket.emit("FromAPI", this.resp);
      console.log(this.resp);
    } 
    catch (error) {
      
      console.error(`Error: ${error.code}`);
    }
  };

Json placeholder URL's and many other are returning the data in console.but this url returns error:Undefined. Json 占位符 URL 和许多其他 URL 正在控制台中返回数据。但是这个 url 返回错误:未定义。 Help please/请帮忙/

The problem here is that you're expecting the error in your catch block to have a code, and that's not always what you'll see.这里的问题是你期望你的 catch 块中的错误有一个代码,而这并不总是你会看到的。 In this case, axios is throwing a http error response, which you'll need to handle appropriately.在这种情况下,axios 会抛出 http 错误响应,您需要对其进行适当处理。 Axios has documentation on how to do this Axios 有关于如何执行此操作的文档

You'll want to build out something more robust, but for now the following should work for this specific case, where you're only handling http error responses:您将想要构建更强大的东西,但现在以下内容应该适用于这种特定情况,您只处理 http 错误响应:

const getApiAndEmit = async (socket) => {
  try {
    let response = await axios.get(
      "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/findByDistrict?district_id=571&date=25-05-2021"
    );
    //socket.emit("FromAPI", this.resp);
    console.log(response);
  } catch (error) {
    console.error(`Error: ${error.message}`);
  }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM