Home > Back-end >  Making API Request with JavaScript
Making API Request with JavaScript

Time:02-17

I have an assignment to complete a function that makes API requests using a name. This request will return a json object and this object has a 'height' field that the function should return. I tried but my solution odes not seem to work. Below is my code. Can someone point me in the right direction?

async function getHeight(name) {

  let url = "sample url"
  https.get(url, (resp) => {
  let data = '';

    resp.on('data', (chunk) => {
      data  = chunk;
  });

  resp.on('end', () => {
    let result = (JSON.parse(data));
    let result_data = result[data];
    if(result_data == null){
      return -1
    } else{
      let cataJson = (JSON.parse(result_data));
      return cataJson["height"];
    }
  });

  }).on("error", (err) => {
    return -1;
  });
}

CodePudding user response:

   async function getHeight(name) {
     let url = "sample url"
     try {
         let res = await fetch(url);
         return await res.json();
     } catch (error) {
         console.log(error);
    }
}

this code should be some thing like what you need. you make a get request to the url then you parse the given data to json format then the function returns that data.

CodePudding user response:

You can use fetch with promise like this.

async function getHeight(name) {
  return new Promise((resolve, reject)=>{
      let url = "sample URL"
       fetch(url)
         .then(res=>res.json())
         .then(data=>{
            let result = (JSON.parse(data));
            let result_data = result[data];
            if(!result_data)resolve(-1)
            else resolve((JSON.parse(result_data)).height)
         })
         .catch(e=>{reject()})
  })
}

And to call the function

async function main(){
  try{
    var height = await getHeight("John");
    console.log(height)
   }catch(e){
     console.log("Error Fetching height")
   }
}
main()

CodePudding user response:

 const getHeight = async (name) {
     let url = "url"
     try {
         let res = await fetch(url,{
             method: "GET"
          );

          if (res.ok == true) {
         return await res.json();
         } else {
         throw new Error("error")
        }
     } catch (error) {
         console.log(error);
    }
}

  • Related