0

i'm trying to send this HTTP request through my function but it returns undefined no matter what

it's a very basic request and i don't understand why this is happening

if i copy and paste the URL into my browser it works and shows the desired JSON

i tried this function on my browser's console using random id and my api key and still return undefined all the same

function getSummary(id){
 let url2=`https://api.spoonacular.com/recipes/${id}/summary?apiKey=${key}`;
 let xhr2=new XMLHttpRequest();
 xhr2.responseType='json';
 xhr2.onreadystatechange=()=>{
 if(xhr2.readyState==XMLHttpRequest.DONE){
 return xhr2.response;
 }
 }
 
 xhr2.open('GET',url2);
 xhr2.send();
}

link to the API's doc

asked Jun 23, 2020 at 16:12
1
  • i include it in the url as instructed by the API's documentation, again: pasting the url in my browser's url bar returns the desired result but the http request in my function doesn't Commented Jun 23, 2020 at 16:24

1 Answer 1

1

You are using the return statement inside of an arrow function and it does not return out of the main function.

xhr2.onreadystatechange=()=>{
 //returns out of this function ^
 if(xhr2.readyState==XMLHttpRequest.DONE){
 return xhr2.response;
 }
}

Instead of creating a function to return the response text you need to run a function with the response text as an argument:

let url2=`https://api.spoonacular.com/recipes/${id}/summary?apiKey=${key}`;
let xhr2=new XMLHttpRequest();
xhr2.responseType='json';
xhr2.onreadystatechange=()=>{
 if(xhr2.readyState==XMLHttpRequest.DONE){
 //seperate function
 run(xhr2.response);
 }
 } 
xhr2.open('GET',url2);
xhr2.send();
function run(text){
 console.log(text);
};
answered Jun 23, 2020 at 16:21
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.