How Can I Create A JavaScript HTTP Request?

Introduction

  • You may use the built-in XMLHttpRequest object or the more recent get() function to send an HTTP request in Javascript.

Here are examples of how to use each :

Using XMLHttpRequest

// 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