To retrieve data from a server, employ the get method in JavaScript. You can request any API that provides responses in either JSON or XML format. The sole argument required for the Fetch method is the URL from which you are requesting data, and this method also yields a promise.
Send a Request using Fetch
The JavaScript Fetch API initiates a request to a specified URL. Upon successful transmission of the request, it presents the corresponding response. Conversely, if the request fails to be sent, an error message will be displayed.
Syntax
The syntax provided below demonstrates how to utilize the fetch API method with JavaScript to send a request to a specified URL.
fetch('url')
.then(response => { //handle request});
.then(error = > { //handle error});
- We pass a configuration object and the endpoint's URL to the fetch method.
- We submitted the given information in our HTML or Javascript components shown as an output.
Reading response using Fetch API
The JavaScript Fetch API facilitates sending a request to a specified URL and subsequently retrieves a response from the API. Upon successful completion of the request, the API processes it and returns the corresponding data.
Syntax
The syntax provided below illustrates the utilization of the fetch API method in JavaScript for obtaining the response from a specified URL.
fetch('url')
.then(response => response.json())
.then(data = > console.log(data));
Parameters:
This method takes two arguments, although one of the parameters is mandatory.
- URL: This represents the destination URL to which the request will be directed.
- Options: This parameter is an array consisting of a collection of properties. It is optional and can be specified based on user preference.
Return Value:
- Whether it is resolved or not, it returns a promise.
- The returned information may be in XML or JSON formats.
- It could be a collection of objects or just one object.
Examples
The subsequent illustrations demonstrate the usage of the fetch API method in JavaScript.
Example 1
The illustration demonstrates the fundamental usage of the fetch API through a JavaScript function.
<!DOCTYPE html>
<html>
<head>
<title> Javascript Fetch API </title>
</head>
<body>
<p> Javascript Fetch API </p>
<script>
//get the URL of the data
let url = 'https://jsonplaceholder.typicode.com/users/1';
console.log(url);
//Fetch API method for getting requests
let fetch_Res = fetch(
url);
// fetch variable is the promise to resolve response using.then() method
// display data as an output
fetch_Res.then(resp =>
resp.json()).then(datas => {
console.log(datas)
})
</script>
</body>
</html>
Output
The displayed image illustrates the value of the URL file presented in the console as an output.
Example 2
The following example demonstrates the fundamental usage of the fetch API through a JavaScript function. The data retrieved from the URL is logged to the console via the JavaScript function. Additionally, we can obtain JSON data to be displayed on the web page.
<!DOCTYPE html>
<html>
<head>
<title> Javascript Fetch API </title>
</head>
<body>
<p> Javascript Fetch API </p>
<script>
//get the URL of the data
let url = 'https://jsonplaceholder.typicode.com/users/2';
console.log(url);
//Fetch API method for getting requests
// fetch variable is the promise to resolve response using.then() method
fetch(url)
.then(response => response.json()) // convert to json data
.then(json => console.log(json)) // display data as an output
</script>
</body>
</body>
</html>
Output
The displayed image illustrates the URL file details presented in the console output.
Example 3
The illustration demonstrates the fundamental fetch API approach for dispatching requests through a JavaScript function. When the fetch method is directed to an incorrect URL, JavaScript subsequently logs an error message to the console.
<!DOCTYPE html>
<html>
<head>
<title> Javascript Fetch API </title>
</head>
<body>
<p> Javascript Fetch API </p>
<script>
//get the URL of the data
let url = 'https://jsonpl1aceholder.typicode.com/users/12';
console.log(url);
//Fetch API method for getting requests
// fetch variable is the promise to resolve response using.then() method
fetch(url).then(response => response.json()) // convert to json data
.then(json => console.log(json)) // display data as an output
.catch(error => console.log('URL Request Failed', error)); // Display Catch errors
</script>
</body>
</body>
</html>
Output
The provided image displays the error details presented in the console as a result.
Example 4
This example demonstrates the fundamental use of the fetch API for making URL requests through a JavaScript function. The fetch method transmits the URL and logs the status information to the console. We can retrieve JSON data directly from the console of the web page.
<!DOCTYPE html>
<html>
<head>
<title> Javascript Fetch API </title>
</head>
<body>
<p> Javascript Fetch API </p>
<script>
//get the URL of the data
let url = 'https://jsonplaceholder.typicode.com/users/1';
async function fetchData() {
let response_data = await fetch(url);
// 200: display the response status of the URL
console.log(response_data.status);
// ok
console.log(response_data.statusText);
if (response_data.status === 200) {
let data = await response_data.text();
//display data of the url as output
console.log(data); // 200
}
}
fetchData();
</script>
</body>
</html>
Output
The provided image illustrates the details of a URL file as displayed in the console output.
Example 5
The illustration demonstrates the fundamental utilization of the fetch API for making URL requests through a JavaScript function. The fetch method incorrectly transmits the URL and status information to the console.
<!DOCTYPE html>
<html>
<head>
<title> Javascript Fetch API </title>
</head>
<body>
<p> Javascript Fetch API </p>
<script>
//get the URL of the data
let url = 'https://jsonplaceholder.typicode.com/users1/1';
async function fetchData() {
let response_data = await fetch(url);
// 200: display the response status of the URL
console.log(response_data.status);
if (response_data.status == 404) {
let data = await response_data.text();
console.log("URL does not found");
//display data of the url as output
console.log(data); // 200
}
}
fetchData();
</script>
</body>
</html>
Output
The provided image illustrates the error status displayed in the console as a result.
Example 6
The following example illustrates the fundamental fetch API method for making URL requests through a JavaScript function. We will create a simple HTML form that prompts the user to input a title and body. It is important to note that the ID is generated automatically. In the script, we execute the get method subsequent to adding an event listener function.
<html>
<head>
</head>
<body>
<form id ="form_data" method="post">
<input type = "text", id = "title" placeholder = "Write technology"/>
<br><br>
<input type = "text", id = "user" placeholder = "Write Users"/>
<br><br>
<input type="submit" value="Insert Value">
</form>
<div>
<h3>The data is successfully inserted</h3>
<h4 id="titles"></h4>
<h5 id="bodies"></h5>
</div>
</body>
<script>
//get the variable of the form id for the function
var form_data=document.getElementById('form_data')
//create a function to use fetch api
form_data.addEventListener('submit', function(e){
e.preventDefault()
//use the id of the input tag of the form
var title = document.getElementById('title').value
var user = document.getElementById('user').value
//fetch method with url request
let url ='https://jsonplaceholder.typicode.com/posts';
fetch(url, {
method: 'POST',
//call user input value
body: JSON.stringify({
title: title,
body: user,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
}
})
.then(function(response){
return response.json()})
.then(function(datas)
{
//display data in console
console.log(datas)
//shows user input values
titles = document.getElementById("titles")
bodies = document.getElementById("bodies")
titles.innerHTML = datas.title
bodies.innerHTML = datas.body
}).catch(error => console.error('SEE Error:', error));
});
</script>
</html>
Output
The illustration displays user details presented in both the console and the web page as the result.
Example 7
The example provided demonstrates a simple image being retrieved through a URL request using a JavaScript function. The fetch method is employed to send the URL of the image, which is then transformed into a blob and subsequently rendered on the web page.
<!DOCTYPE html>
<html>
<head>
<title> Javascript Fetch API </title>
</head>
<body>
<p> Javascript Fetch API </p>
<img src = "" id = "flower_data" width = 350 height = 350/>
<script>
//get the URL of the image request
let url = 'https://images.unsplash.com/photo-1672365328426-c2c09b68212e?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=387&q=80';
async function fetchData() {
//use fetch API method
let response_data = await fetch(url);
//converts image into blob method
const blob_data = await response_data.blob();
//display image in html tag
document.getElementById('flower_data').src = URL.createObjectURL(blob_data);
}
fetchData();
</script>
</body>
</html>
Output
The displayed image illustrates the expected outcome of the web page as seen in the output.
Conclusion
In JavaScript, the fetch API method is utilized to handle URL responses and display the associated data. The information is presented in JSON format, as well as in the accompanying image. This method is straightforward yet crucial for developers when managing URL requests and the data they yield.