HTTP Requests With JavaScript Fetch
JavaScript fetch
is an API that allows you to make HTTP requests, such as GET and POST, from a web page. It was introduced in modern browsers to replace the older XMLHttpRequest API and it is supported by most major browsers today. The fetch
API provides a convenient and modern way to perform these requests and it offers several advantages over the XMLHttpRequest API.
The fetch
method is called on the global fetch
object and it returns a Promise that resolves to the Response object representing the response to the request. The fetch
method takes a single argument, which is the URL of the resource you want to fetch, and it returns a Promise that resolves to the Response object representing the response to the request.
Here's a basic example of using the fetch
method to retrieve a JSON resource:
fetch('https://api.example.com/data.json')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
In this example, the fetch
method is used to retrieve a JSON resource from the https://api.example.com/data.json
URL. The .then
method is used to register a callback that will be executed when the Promise returned by fetch
resolves. In this case, the first .then
method is used to parse the JSON data returned in the Response object, and the second .then
method is used to log the parsed data to the console. The .catch
method is used to register a callback that will be executed if there is an error with the request.
One of the advantages of using the fetch
method is that it provides a more modern and flexible API for making HTTP requests. For example, you can easily set the method of the request (GET, POST, etc.), set headers, and send request bodies, as shown in this example:
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'John Doe',
email: 'johndoe@example.com'
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
In this example, the fetch
method is used to make a POST request to the https://api.example.com/data
URL. The second argument to the fetch
method is an options object that is used to configure the request. The method
property is used to set the method of the request to POST, the headers
property is used to set the Content-Type
header to application/json
, and the body
property is used to set the request body.
Another advantage of using the fetch
method is that it provides a more convenient and modern way to handle errors with requests. When using the fetch
method, you can use the .catch
method to register a callback that will be executed if there is an error with the request, as shown in the examples above.
Finally, the fetch
method provides a convenient and modern way to handle the status of a response. The Response object returned by the fetch
method has a status
property that represents the HTTP status code of the response. For example, a status code of 200 indicates a successful response, while a status code of 404 indicates that the resource was not found.
You can use the status
property to perform different actions based on the status of the response. For example, you can use the following code to check if the response was successful and log an error if it was not:
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP Error: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error(error));
In this example, the .then
method is used to check the status of the response. If the response was not successful (i.e., response.ok
is false), an error is thrown with a message indicating the HTTP status code. If the response was successful, the JSON data is returned and logged to the console.
In conclusion, the fetch
API provides a convenient and modern way to make HTTP requests from a web page. It offers several advantages over the older XMLHttpRequest API, such as a more modern and flexible API, a more convenient way to handle errors, and a more convenient way to handle the status of a response. If you need to make HTTP requests from a web page, the fetch
API is a great choice.