How do I make an HTTP request in Javascript?

To make an HTTP request in JavaScript, you can use the XMLHttpRequest object or the newer fetch API. Here's an example of how to use both methods:

How do I make an HTTP request in Javascript?

Using XMLHttpRequest:

javascript
var xhr = new XMLHttpRequest(); xhr.open("GET", "https://api.example.com/data", true); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { var response = JSON.parse(xhr.responseText); console.log(response); } }; xhr.send();

Using fetch API:

javascript
fetch("https://api.example.com/data") .then(function(response) { if (response.ok) { return response.json(); } throw new Error("Network response was not okay."); }) .then(function(data) { console.log(data); }) .catch(function(error) { console.log(error); });

Both methods allow you to specify the URL of the API endpoint you want to send a request to. You can modify the examples above to perform different types of requests (e.g., POST, PUT, DELETE) by changing the request method and adding any necessary request headers or request body payload.

Note that the fetch API is the newer and more modern way of making HTTP requests in JavaScript. It offers a more powerful and flexible feature set compared to XMLHttpRequest. However, both methods are still widely used, and the choice between them depends on the specific requirements of your project and browser compatibility considerations.

Post a Comment

0 Comments