5

What is the best way to send a GET request to the server in vanilla JavaScript?

isopach
  • 1,783
  • 7
  • 31
  • 43
ooooohyesssss
  • 119
  • 1
  • 1
  • 7
  • when you say vanilla JS, do you mean without using any package? – Ashish Modi Feb 17 '20 at 16:08
  • 1
    Does this answer your question? [HTTP GET request in JavaScript?](https://stackoverflow.com/questions/247483/http-get-request-in-javascript) – shkaper Feb 17 '20 at 16:08
  • 1
    What does this have to do with `python-requests`? It's also very different for browser js and the `node.js` tag you also used. Also, what criteria do you use for "best way"? – ASDFGerte Feb 17 '20 at 16:11

7 Answers7

10

In vanilla javascript, you can use the fetch API.

fetch('http://example.com/movies.json')
  .then((response) => {
    return response.json();
  })
  .then((myJson) => {
    console.log(myJson);
  });
  • or more briefly `(await fetch('http://example.com/movies.json')).json()` – Arnaud A Mar 06 '22 at 04:09
  • Beware that `response.json()` here only returns a `Promise`, not the parsed response payload, hence the need for the additional `.then(myJson) => ...` – Raketenolli Mar 30 '22 at 17:02
2

You can do a redirection to do a synchronous GET request:

var url = 'http://domain/path/?var1=&var2=';

window.location = url;
jerkan
  • 685
  • 2
  • 10
  • 28
1

Using the XMLHttpRequest (XHR) Object.

Code example:

const http = new XMLHttpRequest();
const url='/test';
http.open("GET", url);
http.send();

http.onreadystatechange = (e) => {
  console.log('done')
}
Syll
  • 41
  • 2
  • While this is correct, the raw XHR API is outdated. The modern way, which is more elegant and also supports Promises out of the box, is to use fetch. – IceMetalPunk Feb 17 '20 at 17:13
0
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", THE_URL, false ); // false for synchronous request
    xmlHttp.send( null );
    return xmlHttp.responseText;
  • While this is correct, the raw XHR API is outdated. The modern way, which is more elegant and also supports Promises out of the box, is to use fetch. – IceMetalPunk Feb 17 '20 at 17:12
0

You can try with Fetch

function request() {
            fetch('http://example.com/movies.json')
                .then(function(response) {
                    console.log(response.json())
                })
                .then(function(myJson) {
                    console.log(myJson);
                });
        }

        request()
Saul Ramirez
  • 426
  • 2
  • 9
0

I'm not sure if we can claim here a "best way", but you can use

XMLHttpRequest

or if you want to use a library

Axios

Mikel Wohlschlegel
  • 1,364
  • 1
  • 11
  • 23
-1

if you get installt PHP you can use the get_file_content var

 <html>
<script>
var date= "<?php 
echo(file_get_contents('https://apizmanim.com/twilio/zipapi.php?11211?2021/05/14')?>";
document.write(date);
</script>
</html>