How Do I Make an HTTP Request in JavaScript?


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

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'GET', '', 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) {
    } else {
        console.error('Request failed.  Returned status of ' + xhr.status);
// send the request

Using fetch()

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

Learn more here, How to Use XMLHttpRequest in JavaScript?

Next Recommended Reading Asynchronous HTTP Call In JavaScript