April 20, 2023

How to make HTTP requests in Javascript

I wanted to talk about making HTTP requests in Javascript. HTTP requests are a fundamental part of web development, and Javascript provides several ways to make these requests.

First, let's talk about the built-in XMLHttpRequest object. This object provides a way to make HTTP requests, both synchronous and asynchronous. Here's an example of how to use it to make an asynchronous GET request:

javascript
const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1'); xhr.onload = () => { if (xhr.status === 200) { console.log(xhr.responseText); } else { console.log('Request failed. Status code: ' + xhr.status); } }; xhr.send();

This code creates a new XMLHttpRequest object and sets the HTTP method and URL. The onload callback function is called when the request has completed. If the request was successful (status code 200), we log the response text to the console. Otherwise, we log an error message.

Another way to make HTTP requests in Javascript is to use the Fetch API. This API provides a simpler and more flexible interface than XMLHttpRequest. Here's an example of how to use the Fetch API to make the same request as above:

javascript
fetch('https://jsonplaceholder.typicode.com/todos/1') .then(response => { if (!response.ok) { throw new Error('Request failed. Status code: ' + response.status); } return response.json(); }) .then(data => console.log(data)) .catch(error => console.error(error));

This code uses the fetch function to make a GET request and returns a Promise. If the request was successful, we call the json method on the response object to extract the JSON data. Otherwise, we throw an error.

So there you have it! Two ways to make HTTP requests in Javascript. Which one you choose depends on your needs and preferences. Happy coding!