Making an HTTP request is a fundamental operation in web development, allowing web applications to interact with remote servers and retrieve data. In this article, we will explore how to make HTTP requests in JavaScript using the built-in XMLHttpRequest object and the newer fetch API.
XMLHttpRequest Object
The XMLHttpRequest object is a built-in JavaScript API for making HTTP requests. It is compatible with all modern browsers and provides a simple interface for sending and receiving data. Here is an example of how to use the XMLHttpRequest object to make an HTTP GET request:
const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://jsonplaceholder.typicode.com/users'); xhr.onload = function () { if (xhr.status === 200) { const users = JSON.parse(xhr.response); console.log(users); } else { console.error('Request failed. Returned status of ' + xhr.status); } }; xhr.send();
In this example, we create a new XMLHttpRequest object and call the open method to specify the HTTP method and URL of the request. We then set the onload event handler to parse the response data and log it to the console if the request was successful. If the request fails, we log an error message with the status code.
Here are some commonly used methods of the XMLHttpRequest object:
- open(method, url): Specifies the HTTP method and URL of the request.
- setRequestHeader(name, value): Sets an HTTP request header.
- send(data): Sends the HTTP request with optional data.
- abort(): Aborts the HTTP request.
- onreadystatechange: An event handler that is called every time the readyState property changes.
Fetch API
The fetch API is a newer JavaScript API for making HTTP requests. It provides a simpler, more modern interface than the XMLHttpRequest object and supports promises for easier asynchronous programming. Here is an example of how to use the fetch API to make an HTTP GET request:
fetch('https://jsonplaceholder.typicode.com/users') .then(response => { if (!response.ok) { throw new Error('Request failed. Status code: ' + response.status); } return response.json(); }) .then(users => { console.log(users); }) .catch(error => { console.error(error); });
In this example, we call the fetch method with the URL of the request and the chain promises to handle the response. We first check if the response was successful using the ok property, and if not, we throw an error. We then call the json method to parse the response data and log it to the console. If there is an error, we log it to the console.
Here are some commonly used methods of the fetch API:
- fetch(url, options): Sends an HTTP request with optional options.
- then(onFulfilled, onRejected): Chains promises to handle the response.
- json(): Parses the response body as JSON.
HTTP Request Methods
HTTP request methods are used to indicate the desired action to be performed on the server. There are several HTTP request methods that can be used to send requests from client-side JavaScript applications. In this article, we will discuss each HTTP request method and its specific use case.
- GET: Sends a request to retrieve data from the server.
- POST: Sends a request to submit data to the server.
- PUT: Sends a request to update existing data on the server.
- DELETE: Sends a request to delete data from the server.
HTTP GET Method
The HTTP GET method is used to retrieve data from the server. The client sends a request to the server, and the server responds with the requested data. This method is the most common method used in web applications, as it is used to fetch data from servers.
Here is an example of how to send an HTTP GET request using the fetch() API:
fetch('https://jsonplaceholder.typicode.com/todos/1') .then(response => { if (response.ok) { return response.json(); } throw new Error('Request failed.'); }) .then(data => { console.log(data); }) .catch(error => { console.error(error); });
In the above example, we use the fetch() method to send an HTTP GET request to retrieve data from the server. We then chain promises to handle the response. First, we check if the response was successful using the ok property. If the response was successful, we parse the response body using the json() method. If there is an error, we throw an error and handle it with the catch() method.
HTTP POST Method
The HTTP POST method is used to submit data to the server. The client sends a request to the server, and the server processes the data and responds with a status code to indicate whether the data was successfully submitted. This method is commonly used to create new data on the server.
Here is an example of how to send an HTTP POST request using the XMLHttpRequest object:
const xhr = new XMLHttpRequest(); xhr.open('POST', 'https://jsonplaceholder.typicode.com/todos'); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = () => { if (xhr.status === 201) { console.log(xhr.response); } else { console.error('Request failed. Status code: ' + xhr.status); } }; xhr.send(JSON.stringify({ title: 'Buy milk', completed: false }));
In the above example, we use the XMLHttpRequest object to send an HTTP POST request to submit data to the server. We use the open() method to specify the HTTP method and URL of the request. We also use the setRequestHeader() method to set the content type of the request. After that, we set up an onload event handler to handle the response. Finally, we call the send() method to send the request with the data we want to submit to the server in JSON format.
HTTP PUT Method
The HTTP PUT method is used to update existing data on the server. The client sends a request to the server with the updated data, and the server processes the data and responds with a status code to indicate whether the data was successfully updated. This method is commonly used to update existing data on the server.
Here is an example of how to send an HTTP PUT request using the fetch() API:
fetch('https://jsonplaceholder.typicode.com/todos/1', { method: 'PUT', body: JSON.stringify({ id: 1, title: 'Buy milk', completed: true }), headers: { 'Content-type': 'application/json; charset=UTF-8' } }) .then(response => response.json()) .then(json => console.log(json)) .catch(error => console.error('Error:', error));
In the above example, we sent an HTTP PUT request to update an existing to-do item on the server. We specified the method property as 'PUT' in the fetch() options and sent the updated data in the request body. We also set the Content-Type header to 'application/json; charset=UTF-8' to indicate that we were sending JSON data.
After sending the request, we chained a then() method to handle the response. We parsed the response body using the json() method and logged the response to the console.
HTTP DELETE Method
The HTTP DELETE method is used to delete existing data on the server. The client sends a request to the server to delete the data, and the server responds with a status code to indicate whether the data was successfully deleted. This method is commonly used to delete existing data on the server.
Here is an example of how to send an HTTP DELETE request using the fetch() API:
fetch('https://jsonplaceholder.typicode.com/todos/1', { method: 'DELETE' }) .then(response => { if (response.ok) { console.log('Todo item deleted'); } else { console.error('Request failed.'); } });
In the above example, we use the fetch() method to send an HTTP DELETE request to delete an existing to-do item on the server. We specify the method property as 'DELETE' in the fetch() options.
After sending the request, we check if the response was successful using the ok property. If the response was successful, we log a message to the console. Otherwise, we handle the error with the catch() method.
Tags:
- javascript http request
- javascript http get request
- javascript http request post
- javascript http request json
- javascript post request example
- http get request example
- make http request java
- node js http request
- how do i create an http request
- javascript http post request
- javascript get request example
- what are http requests in javascript
- how to make a http request in javascript
- what is http request with an example
- http request javascript
- http request wiki
- http.request node
- send json post request javascript
- send post request php
- get and post method in html examples
- http get example url
- get request online
- http get request example java
- https request example
- http methods wiki
- http methods patch
- http head request example
- http options method
- send post request in url
Conclusion
Making HTTP requests in JavaScript is essential for web development, and the XMLHttpRequest object and fetch API provide powerful tools for sending and receiving data. By using the methods and techniques we covered in this article, you can make HTTP requests in your own web applications and handle responses in a variety of ways.