Javascript fetch
is a native method to send API requests while keeping a clear code. In addition to requests GET
Used by default, the API also allows you to send, modify or delete data.
What is JavaScript fetch
And what is it for?
Javascript fetch
is a way to make API requests with promised. This type of interaction prevents the code from becoming confused and offers in addition to many other functions. Javascript fetch
Send a Request to a desired server and executes it in the background. We explain to you in the following paragraphs its operation as well as the possibilities that the API fetch
offers you.
Web accommodation
Flexible, efficient and safe web accommodation
- SSL certificate and DDOS protection
- Data backup and restoration
- Assistance 24/7 and personal advisor
The advantages of a promised object
To be able to understand the functioning of JavaScript fetch
it is necessary to take a look at the Promised objects. The promise, which have been introduced with JavaScript ES6, must allow or facilitate the Asynchronous operations. As its name suggests, a promised object is a kind of promise: if it is filled by operating the code, we obtain a value. If the promise cannot be held, there is an error object in response. Inasmuch as replacement or supplement of a callbackthe promise allow more fluid asynchronous management and improve the clarity of the code.
Promise may have states » hanging » (on hold), » fulfilled « (Satisfied) or » rejected (Rejected).
- hanging : The operation has not yet been executed or canceled.
- fulfilled : The operation was successfully performed.
- rejected : the operation failed.
In the case of « Fulfilled » and « rejected », you can react with methods like then()
Or catch()
. Javascript fetch
uses these possibilities and uses promise to execute an XHR request to a server.
Advice
The perfect use of GitHub: With Deploy Now of Ionos, you directly deploy the code changes and can follow the adjustments in real time. Choose the price that best suits your needs!
JavaScript operation fetch
JavaScript's basic syntax fetch
is quite simple to explain. She looks like this:
The method can take into account two arguments. On the one hand, an URL, which is registered with quotes between the two parentheses. On the other hand, an object with options, which is however optional. It is used as a result of the instruction itself.
To better illustrate operation and structure, we use the following code example:
fetch(url)
.then(function() {
})
.catch(function() {
});
javascript
In the first step, we thus specify as a parameter the URL of the theoretical API. Then comes the promised method then()
to which a function is added. This must be executed when the promise returns the variable resolve
. resolve
is used when an action must be declared as successful. The function of then()
Contains the necessary code to process data received from the API.
Below, we used the method catch()
. This is called when the variable reject
returned. reject
is expressed if the API cannot be called or if other errors occur. In this case, the function is performed inside catch()
. Thus, with only three lines, you are prepared for all eventualities and can initiate API requests with JavaScript fetch
.
Queries GET
with JavaScript fetch
You can use JavaScript fetch
To recover data from an API. In the following example, we make a request GET
. This is the Standard adjustment javascript fetch
. For this, we again take an example of URL. This will respond with a promise to which we will apply the method then()
. We then convert the server's response to a JSON object and again use a method then()
To display the data thus obtained in the console. An appropriate code for this operation could look like this:
fetch("https://exempledurl.com/api")
.then((response) => response.json())
.then((json) => console.log(json));
javascript
Send data with POST
Even if the request GET
is the standard, it is also possible to carry out operations POST
with JavaScript fetch
. These are used for Send data. Once again, we must first indicate the desired URL. Then we use the key method
To define the type of request. In our case, it has the value « post ». Two other compulsory keys follow: body
And headers
.
body
Defines the data that must be sent to the server. In this example, the data sent include fields title
And body
. In addition, we use JSON.stringify
To convert the data to a character string. headers
is used to define the data type that must be sent to the server. In our case, it must be JSON data and we choose the standard UTF-8 coding. The two keys must be defined for a request POST
. For our example above, the corresponding code would look like this:
fetch("https://exempledurl.com/api", {
method: "POST",
body: JSON.stringify({
title: "Le titre se trouve ici",
body: "Le contenu se trouve là",
}),
headers: {
"Content-type": "application/json; charset=UTF-8",
},
})
.then((response) => response.json())
.then((json) => console.log(json));
javascript
Update objects with PUT
Or PATCH
With a request PUT
Or PATCH
an object can be completely updated, which is also possible with JavaScript fetch
. The approach is similar to the previous example. There must be an option again body
with character chain, or JSON.stringify
. The content type is indicated with application/json
. For our example, here is the code:
fetch("https://exempledurl.com/api", {
method: "PUT",
body: JSON.stringify({
title: "Le titre se trouve ici",
body: "Le contenu se trouve là",
}),
headers: {
"Content-type": "application/json; charset=UTF-8",
},
})
.then((response) => response.json())
.then((json) => console.log(json));
javascript
Instead of PUT
you can also use PATCH
.
Delete objects with DELETE
If you want to use JavaScript fetch
To delete an object, you can use a request DELETE
. If necessary, you can also use the method then()
. Here is a corresponding example:
fetch("https://exempledurl.com/api", {
method: "DELETE"
})
.then(() => {
element.innerHTML = "Supprimé avec succès";
})
.catch((error) => {
console.error('Erreur lors de la requête:', error);
});
javascript