简体   繁体   中英

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.

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. 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. In this case, axios is throwing a http error response, which you'll need to handle appropriately. Axios has documentation on how to do this

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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