How to make an HTTP request in Javascript?


In JavaScript, you can make an HTTP request using the built-in fetch() function or the XMLHttpRequest object.

Here’s an example of making an HTTP request using fetch():

  .then(response => response.json())
  .then(data => {
  .catch(error => {

This code sends an HTTP GET request to, and when the response is received, it is converted to JSON using the json() method of the response object. Then, the JSON data is logged to the console.

Here’s an example of making an HTTP request using XMLHttpRequest:

const xhr = new XMLHttpRequest();'GET', '');
xhr.onload = () => {
  if (xhr.status === 200) {
  } else {
xhr.onerror = () => {
  console.error('Network error');

This code creates a new XMLHttpRequest object, opens a connection to, and defines a callback function to handle the response. If the response status is 200 (OK), the response text is logged to the console. If there is an error, an error message is logged to the console. Finally, the request is sent using the send() method.


How useful was this post?

Click on a star to rate it!

Average rating 4 / 5. Vote count: 1

No votes so far! Be the first to rate this post.

Leave a Comment

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

Scroll to Top