Caxios.
General purpose HTTP request library with consistent behaviour.
Works in node.js and in the browser.
It is 100% Axios compatible, with some extra defaults and features.
Installation
npm install caxios
and then
const getJSON postJSON = ; // basic data fetching; // posting JSON data (for ex.: a form) and handling server-side validation
Defaults
Caxios uses the following defaults:
- request timeout = 3 seconds (by default Axios uses infinity)
post
,put
andpatch
methods sendContent-Type: application/json
header (by default Axios sendsContent-Type: application/x-www-form-urlencoded
)- all utility functions with with JSON suffix (
getJSON
,postJSON
,putJSON
,delJSON
) sendAccept: application/json
header (by default Axios sendsapplication/json, text/plain, */*
for all requests)
Caxios does NOT modify the global axios
instance.
Features
While Axios is an excellent library, its default behaviour may not be ideal. Caxios aims to address this by introducing the following features:
- easier and consistent error handling
- utility functions for making requests that accept only JSON responses
- support for HTTP status code
422
-Unprocessable Entity
(used for validation errors) - support for malformed JSON response handling
Rejected request error objects are extended with additional methods:
isFormat()
- true if the client expected JSON response, but server returned malformed JSONisCancel()
- true if the request was cancelled by the clientisNetwork()
- true for any network error (timeout, server unavailable, CORS etc.)isValidation()
- true if responsestatus
==422
(used for validation errors)
These error types are mutually exclusive, so only one of those methods returns true for any error.
Examples
application/json
responses
Send a request that accepts only const getJSON = ; // Axios axios
Easier cancel token passing
const getJSON makeCancelSource = ;const cancelSource = ;cancelSource; ; // true // Axios axios ; // true
Easy error handling
; // Axios axios ;
Consistent JSON response format error handling
; // Axios swallows JSON parsing errors, so you have to// manually verify response format in the successful response handler
Special case for validation errors (422 HTTP status code)
;