javascript

How to make HTTP requests using Javascript Only

In JavaScript, you can make an HTTP request using the built-in XMLHttpRequest object or the new fetch() function. We will explain all methods in this post.

How to make HTTP requests using Javascript Only

To make an HTTP request using Javascript only you can use the XMLHttpRequest object or you can also use the function fetch().


Send HTTP GET Request

Below are some code examples that can be used to send a GET request. We will describe different methods to send headers and data in the HTTP request.


HTTP GET request using XMLHttpRequest:

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api/endpoint');
xhr.onload = function() {
  if (xhr.status === 200) {
    console.log(xhr.responseText);
  } else {
    console.error('Request failed.  Returned status of ' + xhr.status);
  }
};
xhr.send();

HTTP GET request using fetch() function.

fetch('https://example.com/api/endpoint')
  .then(response => {
    if (!response.ok) {
      throw new Error('Request failed');
    }
    return response.json();
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error(error);
  });

[GET request with headers] - XMLHttpRequest

To send an HTTP GET request with headers using XMLHttpRequest, you can set the headers using the setRequestHeader() method before calling the send() method. Here's an example:

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/api/data');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Authorization', 'Bearer my_token');
xhr.onload = function() {
  if (xhr.status === 200) {
    console.log(xhr.responseText);
  } else {
    console.error('Request failed.  Returned status of ' + xhr.status);
  }
};
xhr.send();

[GET request with headers] - fetch() function

To send an HTTP GET request with headers using the fetch() function, you can pass an options object as the second argument to the fetch() function. Here's an example:

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

[GET Request with data] - XMLHttpRequest

const xhr = new XMLHttpRequest();
const data = {
  name: 'John Doe',
  age: 30
};

const params = Object.keys(data).map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`).join('&');

xhr.open('GET', `https://example.com/api/endpoint?${params}`);
xhr.onload = function() {
  if (xhr.status === 200) {
    console.log(xhr.responseText);
  } else {
    console.error('Request failed.  Returned status of ' + xhr.status);
  }
};
xhr.send();

[GET Request with data] - using fetch()

const data = {
  name: 'John Doe',
  age: 30
};
const params = new URLSearchParams(data);
fetch(`https://example.com/api/data?${params}`, {
  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);
});

In this example, we're creating a data object and converting it to a URLSearchParams object. Then we're using the resulting URL with the encoded query parameters in the fetch() function.



Send HTTP POST Request

here are examples of how to send an HTTP POST request using XMLHttpRequest and the fetch() function in JavaScript.

[HTTP POST Request with headers and raw data] - XMLHttpRequest

const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://example.com/api/data');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.setRequestHeader('Authorization', 'Bearer my_token');
xhr.onload = function() {
  if (xhr.status === 200) {
    console.log(xhr.responseText);
  } else {
    console.error('Request failed.  Returned status of ' + xhr.status);
  }
};
const data = {
  name: 'John Doe',
  age: 30
};
xhr.send(JSON.stringify(data));

In this example, we're setting the request method to POST, setting two headers (Content-Type and Authorization) using the setRequestHeader() method, and set the request body using the send() method. We're also stringifying the data object using JSON.stringify() before sending it in the request body.


[HTTP POST Request with headers and raw data] - fetch() function

fetch('https://example.com/api/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer my_token'
  },
  body: JSON.stringify({
    name: 'John Doe',
    age: 30
  })
})
.then(response => {
  if (!response.ok) {
    throw new Error('Request failed');
  }
  return response.json();
})
.then(data => {
  console.log(data);
})
.catch(error => {
  console.error(error);
});

In this example, we're setting the method to POST, setting two headers (Content-Type and Authorization) using the headers property, and setting the request body using the body property. We're also stringifying the data object using JSON.stringify() before sending it in the request body.


[HTTP POST Request with Form Data] - using XMLHttpRequest

To send an HTTP POST request with form data using XMLHttpRequest, you can set the request method to POST using the open() method and set the request headers using the setRequestHeader() method. Then you can create a FormData object, append the form data to it using the append() method, and send the request using the send() method. Here's an example:

const xhr = new XMLHttpRequest();
xhr.open('POST', 'https://example.com/api/data');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('Authorization', 'Bearer my_token');
xhr.onload = function() {
  if (xhr.status === 200) {
    console.log(xhr.responseText);
  } else {
    console.error('Request failed.  Returned status of ' + xhr.status);
  }
};
const formData = new FormData();
formData.append('name', 'John Doe');
formData.append('age', 30);
xhr.send(formData);

In this example, we're setting the request method to POST, setting two headers (Content-Type and Authorization) using the setRequestHeader() method, and creating a FormData object with the form data. We're then appending the data to the FormData object using the append() method and sending the request using the send() method.


[HTTP POST Request with Form Data] - using fetch() function

To send an HTTP POST request with form data using the fetch() function, you can pass a FormData object as the body property of the options object. Here's an example:

const formData = new FormData();
formData.append('name', 'John Doe');
formData.append('age', 30);
fetch('https://example.com/api/data', {
  method: 'POST',
  headers: {
    'Authorization': 'Bearer my_token'
  },
  body: formData
})
.then(response => {
  if (!response.ok) {
    throw new Error('Request failed');
  }
  return response.json();
})
.then(data => {
  console.log(data);
})
.catch(error => {
  console.error(error);
});

In this example, we're creating a FormData object with the form data, passing it as the body property of the options object, and setting one header (Authorization) using the headers property.


Was this helpful?