make a http get request in javascript

To make an HTTP GET request in JavaScript, you can use the XMLHttpRequest object or fetch API. Here's an example using the XMLHttpRequest object:

index.tsx
const url = 'https://example.com/data';
const xhr = new XMLHttpRequest();

xhr.open('GET', url, true);

xhr.onload = function() {
    if (xhr.status === 200) {
        const data = JSON.parse(xhr.responseText);
        console.log(data);
    }
};

xhr.send();
260 chars
14 lines

In the above code block, we create a new XMLHttpRequest object and specify the method (GET), URL, and whether or not the request should be asynchronous (true). We then define a callback function for the onload event, which is triggered when the response is received. If the response status is 200 (OK), we parse the response text as JSON data and log it to the console.

Alternatively, you can use the fetch API to make an HTTP GET request:

index.tsx
const url = 'https://example.com/data';

fetch(url)
    .then((response) => response.json())
    .then((data) => console.log(data));
133 chars
6 lines

In this code block, we call the fetch method with the URL as an argument. This returns a Promise that resolves to the response. We then use the json method to parse the response body and return another Promise that resolves to the JSON data. Finally, we log the data to the console.

gistlibby LogSnag