With JavaScript, How Do I Create an HTTP Request?

Introduction

To make an HTTP request in Javascript, you can use the built-in XMLHttpRequest object or the newer fetch() method.

With JavaScript, you may use the built-in XMLHttpRequest object or the newer fetch API to make an HTTP request. Here’s an example of an HTTP GET request made with XMLHttpRequest:

Here are examples of how to use each:

// create a new XMLHttpRequest object
const xhr = new XMLHttpRequest();
// define the HTTP method, URL, and async flag
xhr.open('GET', 'https://example.com/data.json', true);
// set any headers (optional)
xhr.setRequestHeader('Content-Type', 'application/json');
// define a callback function to handle the response
xhr.onload = function() {
    if (xhr.status === 200) {
        console.log(xhr.responseText);
    } else {
        console.error('Request failed.  Returned status of ' + xhr.status);
    }
};
// send the request
xhr.send();

Using fetch()

fetch('https://example.com/data.json', {
    method: 'GET',
    headers: {
        'Content-Type': 'application/json'
    }
}).then(response => {
    if (!response.ok) {
        throw new Error('Request failed');
    }
    return response.json();
}).then(data => {
    console.log(data);
}).catch(error => {
    console.error(error);
});

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories