Axios vs Fetch API
Axios vs Fetch API
@shivendra-dwivedi
1: API Creation / Call Syntax
Axios: There are 3 ways to do this in axios
1: Main axios() method: axios(config)
@Shivendra Dwivedi
3: Axios custom instance methods: axios.create(config)
Step 1
Step 2
Step 1
Step 2
Step 3
@Shivendra Dwivedi
2: Default Setting:
Axios: Here we can set default options at two levels
global and instance level. Default options will be applied
on all the API calls that we will make.
Global Level:
Instance Level:
@Shivendra Dwivedi
fetch API:
No default setting option is available. We must repeat
headers & config in every request.
@Shivendra Dwivedi
3: Interceptors:
Axios: Interceptors are functions that run before a
request is sent or before a response is handled by then()
or catch().
Think of them as middleware for HTTP requests.
Request Interceptor
Response Interceptor
@Shivendra Dwivedi
4: Configuration Options:
Axios:
Configuration options let us customize how our API call
behaves, like setting timeouts, transforming data,
showing progress, etc.
1: transformRequest / transformResponse:
transformRequest used to alter the data which will be
send to the server before it’s being send.
@Shivendra Dwivedi
parsing the data before
it’s handled by the then()
or catch() blocks
2: onUploadProgress / onDownloadProgress:
With these we can track upload and download progross in
axios.
tracking download
pregress
@Shivendra Dwivedi
3: timeout: Defines the maximum time (in ms) to wait for
a response before canceling the request. If the server
doesn't respond within that time, the request is canceled
internally.
@Shivendra Dwivedi
5: Error handling:
Axios: Simple & Developer-Friendly. Axios automatically
throws errors for: Network issues, Timeout
Non-2xx HTTP status codes (including 404, 500).
fetch API: Fetch does not throw errors for HTTP failures
like 404 or 500. Only throws on network failures (e.g., no
internet). We must check response.ok manually.
@Shivendra Dwivedi
6: JSON Handling:
Axios: It handles JSON for you in both directions
(Request / Response) :
Auto stringifies request body, Auto parses JSON response.
No need to manually call JSON.stringify() or res.json().
manually handling
@Shivendra Dwivedi
7: API call Canceling:
Axios: Axios previously used CancelToken, but it's now
deprecated. Modern Axios from v0.22.0 uses the
standard AbortController, same as Fetch:
@Shivendra Dwivedi
8: Backend compatibility:
Axios:
Axios was not always available natively in the backend
(Node.js). Axios has always been a third-party HTTP client
library that needs to be installed manually.
@Shivendra Dwivedi
Node.js v = 18+
Node.js v < 18
@Shivendra Dwivedi
Was this helpful?
, &
for more JavaScript insights!
Shivendra Dwivedi
@Shivendra-Dwivedi
Connect