Fetch API vs Axios for HTTP requests
Fetch API vs Axios for HTTP requests which one is better and why?
## Fetch API
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across a network.
### Syntax
fetch(input, init);### Parameters
- input - The URL you wish to fetch.
- init - An object with any custom settings that you want to apply to the request. The possible options are:
- method - The request method, e.g.,
GET,POST,PUT,PATCH,DELETE. The default isGET. - headers - Any headers you want to add to your request, contained within a Headers object or an object literal with ByteString values.
- body - Any body that you want to add to your request: this can be a
Blob,BufferSource,FormData,URLSearchParams, orUSVStringobject. Note that a request using the GET or HEAD method cannot have a body. - mode - The mode you want to use for the request, e.g.,
cors,no-cors,same-origin, ornavigate. The default iscorswhich stands forCross-Origin. - credentials - The request credentials you want to use for the request:
omit,same-origin, orinclude. The default issame-origin. - cache - The cache mode you want to use for the request:
default,no-store,reload,no-cache,force-cache, oronly-if-cached. - redirect - The redirect mode to use:
follow,error, ormanual. The default isfollow. - referrer - A USVString specifying
no-referrer,client, or a URL. The default isclient. - referrerPolicy - Specifies the value of the referer HTTP header. May be one of
no-referrer,no-referrer-when-downgrade,origin,origin-when-cross-origin,same-origin,strict-origin,strict-origin-when-cross-origin, orunsafe-url. - integrity - Contains the subresource integrity value of the request (e.g., sha256-BpfBw7ivV8q2jLiT13fxDYAeHtYK7DDiZ0L+FL/4vow=).
- method - The request method, e.g.,
### Example
#### TRY-CATCH METHOD
The try catch method is an efficient way to handle errors in code. Using the fetch API with a try-catch block is a good way to implement error handling with the fetch API because more can be done and it can ensure clean and a readable code.
Using the {JSON} Placeholder API, we can fetch data from the API and handle errors with the try-catch method.
const = 'my-token';
type = Error & {
?: { : Error; : Response };
};
try {
// Fetch data from the API
const = await ('https://jsonplaceholder.typicode.com/todos/1', {
: 'GET', // method can be GET, POST, PUT, PATCH, DELETE depending on the API endpoint definition
: 'cors', // mode to use for request
: {
: `Bearer ${}`, // Add token to the header if needed for authentication and authorization
'Content-Type': 'application/json' // Add content type if needed
}
});
// Check if the response is ok and throw an error to the catch block if not
if (!.) throw new ('Something went wrong', { : { } });
// perform some action with the response
// make toast notification
// Parse the response to JSON
const = await .();
// do something with the data
} catch () {
let : ;
if ( instanceof ) = as ;
else = new ('Error fetching todo', { : { } }) as ;
// since the error was thrown from the try block with the response object, we can access the response object from the error object
// Handle errors based on the status code
switch (.?.?.) {
case 400: // bad request - invalid data
// perform some action
break;
case 401: // unauthorized - invalid token
// perform some action
break;
// others
default:
// perform some action
break;
}
}#### USING THE PROMISES-CHAIN METHOD
The promises-chain method is another way to use the fetch API. This method is not as efficient as the try-catch method because it is not as readable and might not be as clean as the try-catch method.
const = 'my-token';
type = Error & {
?: { : Error; : Response };
};
// Fetch data from the API
('https://jsonplaceholder.typicode.com/todos/1', {
: 'GET', // method can be GET, POST, PUT, PATCH, DELETE depending on the API endpoint definition
: 'cors', // mode to use for request
: {
: `Bearer ${}`, // Add token to the header if needed for authentication and authorization
'Content-Type': 'application/json' // Add content type if needed
}
})
.(() => {
// Check if the response is ok and throw an error to the catch block if not
if (!.) throw new ('Something went wrong', { : { } });
// perform some action with the response
// make toast notification
// Parse the response to JSON
return .();
})
.(() => {
// do something with the data
})
.(() => {
let : ;
if ( instanceof ) = as ;
else = new ('Error fetching todo', { : { } }) as ;
// handle
});## Axios
Axios is a promise-based HTTP client for the browser and Node.js. It has a convenient and modern API simplifying asynchronous HTTP request and response handling.
### Syntax
axios(url, config);Published on June 21, 2023
5 min read
Found an Issue!
Find an issue with this post? Think you could clarify, update or add something? All my posts are available to edit on Github. Any fix, little or small, is appreciated!
Edit on GitHubLast updated on
