How to make an HTTP request in JavaScript?

Web Development

Making HTTP Requests in JavaScript, , actually there are two way to do this.

JavaScript is a powerful programming language that can be used to create dynamic web applications. One of the most important tasks that any web application needs to perform is making HTTP requests. In this post, we’ll take a look at two of the most popular ways to make HTTP requests in JavaScript: the XMLHttpRequest API and the fetch API.

Using the XMLHttpRequest API

The XMLHttpRequest API is an older method of making HTTP requests in JavaScript. It’s been around since the early days of web development and is supported by all modern web browsers. Here’s an example of how to use the XMLHttpRequest API to make a GET request:

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

In this example, we first create a new XMLHttpRequest object, then we call the open method to specify the type of request (GET) and the URL we want to make the request to. We also set the third parameter to true, which indicates that the request should be made asynchronously.

We then set an onreadystatechange event handler, which is called whenever the state of the request changes. In this case, we’re checking if the readyState is 4 (which means that the request has completed) and the status is 200 (which means that the request was successful). If both of these conditions are true, we log the responseText to the console.

Finally, we call the send method to send the request.

Using the fetch API

The fetch API is a newer method of making HTTP requests in JavaScript, and is considered to be a more modern and simpler alternative to the XMLHttpRequest API. Here’s an example of how to use the fetch API to make a GET request:

fetch("https://www.example.com")
.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.log(error))

In this example, we call the fetch function and pass in the URL of the resource we want to fetch. This returns a promise that is resolved with a Response object. We then chain .then method to handle the response, in this example, we call the text() method on the response object to parse it as a string, then we log the data to the console.

It’s also worth noting that you can also use the fetch function to make other types of requests, such as POST, PUT, and DELETE, by specifying the request method as the first argument and a request body as the second argument.

fetch("https://www.example.com", {
    method: "POST",
    body: JSON.stringify({key: "value"}),
      headers: {
        "Content-Type": "application/json"
    }
})
.then(response => response.text())
.then(data => console.log(data))
.catch(error => console.log(error))

In this example, we’re making a POST request to the same URL as before, but this time we’re also specifying a request body and a “Content-Type” header. The JSON.stringify method is used to convert a JavaScript object to a JSON string. This request body is sent in the body of the request and specifying the header allows the server to know how to parse the data.

It’s important to note that the fetch API returns a promise, so it’s best practice to always include a catch block to handle errors.

In conclusion, both XMLHttpRequest and fetch API are a powerful tools that you can use to make HTTP requests in JavaScript. The fetch API is considered to be more modern and easier to use, but the XMLHttpRequest API is still widely supported and can be used in older browsers.

Keep in mind that security considerations, such as CORS headers, should always be taken into account when making requests.

Using Axios

Another way of making HTTP request in JavaScript is by using axios, which is a popular JavaScript library for making HTTP requests. It works in a similar way to the fetch API, but provides a more powerful and flexible interface, allowing for better handling of errors, easier configuration, and more.

Here is an example of how to make a GET request using axios:

axios.get('https://www.example.com')
  .then(response => console.log(response.data))
  .catch(error => console.log(error))

You can also use axios to make other types of requests, like POST, PUT and DELETE, and configure various options, such as headers, timeout, and auth credentials. Here’s an example of how to make a POST request with a JSON payload and a custom header using axios:

axios.post('https://www.example.com', {
  key: "value"
}, {
  headers: {
    'Content-Type': 'application/json',
    'Custom-Header': 'value'
  }
})
.then(response => console.log(response.data))
.catch(error => console.log(error))

axios also has a wide browser and Node.js compatibility, which means you can use it for both client-side and server-side applications.

In summary, axios is a convenient and versatile library that provides a powerful and flexible interface for making HTTP requests in JavaScript. It is also supported across a wide range of platforms and devices, and offers a range of options and settings to handle various request and response types.

Video Tutorial coming soon .

https://www.youtube.com/c/MenyhartMedia

Want to become a web developer ?

Get complete web development courses on HTML, CSS , JavaScript, Bootstrap, Visual Studio Code, Responsive design and much more…

Love Podcast about web development?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.