Search Tools Links Login

HTTP Request in Javascript


There are several ways to make an HTTP request in JavaScript. One of the most common ways is using the XMLHttpRequest (XHR) object, which is supported by all modern browsers.

Here's an example of how to use XMLHttpRequest to send a GET request to retrieve a JSON file from a server:

const xhr = new XMLHttpRequest();

xhr.open('GET', 'https://example.com/data.json');
xhr.onload = function() {
  if (xhr.status === 200) {
    console.log(xhr.responseText); // the response text is the JSON file
  } else {
    console.error('An error occurred: ', xhr.statusText);
  }
};
xhr.send();

Alternatively, you can use the fetch() function, which is a modern way to make HTTP requests and is supported by most modern browsers.

Here's an example of how to use fetch() to send a GET request to retrieve a JSON file from a server:

fetch('https://example.com/data.json')
  .then(response => response.json()) // parse the response as JSON
  .then(data => console.log(data)) // log the data
  .catch(error => console.error(error));

Both XMLHttpRequest and fetch() allow you to make other types of HTTP requests, such as POST, PUT, and DELETE, as well as specify request headers and send data in the request body.

About this post

Posted: 2022-12-21
By: dwirch
Viewed: 223 times

Categories

Tip

Tutorial

Scripting

Attachments

No attachments for this post


Loading Comments ...

Comments

No comments have been added for this post.

You must be logged in to make a comment.