Data Fetching from the Server
Do you know what AJAX is? It seems to be an "old" concept today, it allows us to use JavaScript to send asynchronous data requests to the server and update the rendering of the page locally.
I still remember the excitement when I first knew this concept, I knew that a webpage was no longer just a piece of boring HTML code.
Today, we will focus on one of the most important features in a web application: Data Fetching from the Server.
The Fetch Method
The fetch()
method is a global method that provides a straightforward, logical method to fetch resources asynchronously over the network.
It gives back a Promise
that resolves into a Response
object, which signifies the outcome of the request.
Syntax
const fetchPromise = fetch(url, options);
fetchPromise.then(res => {
// success response
// ...
}).catch(ex => {
// exceptions
// ...
});
- url: defines the resource that you wish to fetch.
- options: optional, an object containing any custom settings you want to apply to the request.
- e.g.
method
,body
,headers
, etc
- e.g.
Basic Example
Let's try to fetch data using the default GET
method.
fetch('https://example.com/books.json')
.then(response => {
return response.json();
})
.then(response => {
console.log(response);
})
.catch(ex => {
console.error(ex);
});
- We use the
fetch()
method to make an HTTP request to the specified URL ("http://example.com/books.json"). - The
fetch()
method returns a Promise that resolves with a Response object. - To extract the JSON response body, we use the
json()
method on the Response object.