Home > Blockchain >  GET Request with JS
GET Request with JS

Time:08-31

i need to send a GET request from my JavaScript function to my python flask app. However, i tried to type the URL with the parameters manually and it worked. But i can't send the same request in a JS function. Response type is HTML.

This is how the URL should look like: http://127.0.0.1:5000/books?rank=2&topic=Self improvement

I tried this, but it didn't work:

function sendRequest() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', '/books', {
        rank: rank,
        topic: topic
    });

    xhr.onload = function() {
        console.log(xhr.response);
    }

    xhr.send();
}

What the URL looked like with this try: http://127.0.0.1:5000/books

Please help!

CodePudding user response:

You're trying to pass the parameters in a POST body (the third argument to open). That won't work for a GET, they have to be in the URL.

The easiest and least error-prone way is to use URLSearchParams (thank you Christopher for pointing that out when I forgot!):

const url = "/books?"   new URLSearchParams({rank, title});

Live Example:

const rank = 42;
const title = "Life, the Universe, and Everything";
const url = "/books?"   new URLSearchParams({rank, title});
console.log(url);

These days, you'd usually use the more modern fetch rather than XMLHttpRequest:

function sendRequest() {
    const url = "/books?"   new URLSearchParams({rank, title});
    fetch(url)
        .then((response) => {
            if (!response.ok) {
                throw new Error(`HTTP error ${response.status}`);
            }
            return response.text(); // Or `.json()` or one of the others
        })
        .then((data) => {
            console.log(data);
        })
        .catch((error) => {
            // ...handle/report error...
        });
}

But if you prefer to use XMLHttpRequest, put the parameters in the URL (and handle errors):

function sendRequest() {
    const xhr = new XMLHttpRequest();
    const url = "/books?"   new URLSearchParams({rank, title});
    xhr.open("GET", url);

    xhr.onload = function () {
        console.log(xhr.response);
    };
    xhr.onerror = function () {
        // ...handle/report error...
    };

    xhr.send();
}

(You can also use string concatenation and encodeURIComponent to build the URL, but it's more work and more error-prone. :-) )

CodePudding user response:

I made a code with fetch() based on the comments above, let me know if you get any errors. Hope this helps, XMLHttpRequest() is not used much due to its complexity.

 async function sendRequest(){
    const url = 'your URL';
     await fetch(url,{
        method: "GET",
        headers: {
          "Content-Type": "application/json",
          "Accept": "application/json"
        
        }
      }).then(response=>{
        if(response.status !=200) {
          throw new Error(`HTTP ERROR:${response.status}`);
        } 
        return response.text()
        }

    ).then(data => {
      console.log(data);
      // convert to html
  
    }).catch(err => {
      console.log(err);
    }) 
  }
  • Related