This is a series of articles about web programming. Here, I would like to share a few knowledge and experience with anyone.
In the first article, I will talk about Axios and Fetch, a knowledge so important in web programming. I hope the article will bring a lot of useful knowledge to everyone.
What is Axios?
Axios is a JavaScript library that provides a promise-based HTTP client for Server (Node.Js) and Client (Browser).
On the server side, it uses the native node.js HTTP module and uses XMLHttpRequest on the client side (Browser). (Quote: axios-http.com)
![]()
Source of image: axios-http.com
Axios provides some outstanding features as follows:
- Create XMLHttpRequests from the client (browser).
- Server: Support make HTTP requests from node.js
- Supports the Promise API.
- Intercept request and response.
- Transform request and response data and cancel requests.
- Client-side support for protecting against XSRF.
- … And many other features.
Using Axios helps us save a lot of time writing code, making the source code more concise and readable.
As a result, Axios has become a widely used library in modern web applications.
What is Fetch API?
The Fetch API is a modern JavaScript interface for making network requests, similar to XMLHttpRequest (XHR). Fetch support for send and receive requests from clients by javascript. Most browsers today support Fetch
The Fetch API has the following interfaces/functions:
- Fetch() global function. This method starts the process of fetching a resource from the network and returns a promise that is a response from the server side. (Quote: developer.mozilla.org)
- Headers: Allow to perform many actions on HTTP request and response headers (get, append, delete,...).
- Request: It represents a resource request. There are many properties in a Request. For example: Request.body, Request.headers, Request.bodyUsed, Request.cache, Request.method, ...
- Response: It represents the response to a request. A few response properties are Response.body, Response.headers, Response.ok, Response.status, … and some methods is Response.error(),
- Response.redirect(), Response.json(), …
Code example:
function handleGetData(url, body) { fetch(url, { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(body), }) .then(function (response) { console.log("response: ", response); return response.json(); }) .then(function (data) { console.log(data); }) .catch(function (err) { console.log("Something went wrong!", err); });}Compare Axios and Fetch.
-
- Automatic format JSON response
- Interceptors are an important feature
- Cancel request
Conclusion.
Source of image: bhmpics.com