Request Methods
Axios provides several request methods corresponding to standard HTTP methods:
axios.get(url[, config])axios.delete(url[, config])axios.head(url[, config])axios.options(url[, config])axios.post(url, data[, config])axios.put(url, data[, config])axios.patch(url, data[, config])
Default Configuration
Global Axios Defaults
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';Custom Instance Defaults
// Set defaults when creating an instance
const instance = axios.create({
baseURL: 'https://api.example.com'
});
// Modify defaults after instance creation
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;Configuration Priority
Configurations are merged based on priority: library defaults in lib/defaults.js, followed by instance defaults, and finally the request’s config parameter. Later configurations override earlier ones.
// Create instance with library defaults (timeout default is 0)
const instance = axios.create();
// Override library's timeout default
instance.defaults.timeout = 2500;
// Override timeout for a specific request
instance.get('/longRequest', {
timeout: 5000
});Request Configuration Object
The request configuration object allows customization of request details, including but not limited to:
url: The request URL.method: The request method, defaults toget.data: Data to send, used forpost,put, andpatchmethods.params: Key-value pairs for URL query strings.headers: Custom request headers.timeout: Request timeout in milliseconds.withCredentials: Whether to include cookies, boolean.responseType: Response type, e.g.,json,arraybuffer,blob,document,text,stream.validateStatus: Function to validate response status; returnstrueto resolve, else rejects.cancelToken: Token for canceling requests.
Complete Configuration Example
{
// `url` is the server URL for the request
url: '/user',
// `method` is the HTTP method used
method: 'get', // default
// `baseURL` is prepended to `url` unless `url` is absolute
baseURL: 'https://some-domain.com/api/',
// `transformRequest` allows modifying request data before sending
// Only applies to `PUT`, `POST`, and `PATCH`
// The last function must return a string, Buffer, ArrayBuffer, FormData, or Stream
transformRequest: [function (data, headers) {
// Transform request data
return data;
}],
// `transformResponse` allows modifying response data before passing to then/catch
transformResponse: [function (data) {
// Transform response data
return data;
}],
// Custom headers
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `params` are URL parameters sent with the request
// Must be a plain object or URLSearchParams
params: {
ID: 12345
},
// `paramsSerializer` is an optional function to serialize `params`
paramsSerializer: function (params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
// `data` is the request body data
// Applies to `PUT`, `POST`, `DELETE`, and `PATCH`
// Must be a string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams, FormData, File, Blob, Stream, or Buffer
data: {
firstName: 'Fred'
},
// Alternative syntax for sending request body data (POST only, sends value only)
data: 'Country=Brasil&City=Belo Horizonte',
// `timeout` specifies the request timeout in milliseconds
timeout: 1000, // default is 0 (no timeout)
// `withCredentials` indicates whether to send credentials with cross-origin requests
withCredentials: false, // default
// `adapter` allows custom request handling for testing
adapter: function (config) {
/* ... */
},
// `auth` for HTTP Basic Auth
auth: {
username: 'janedoe',
password: 's00pers3cret'
},
// `responseType` specifies the data type of the response
responseType: 'json', // default
// `responseEncoding` specifies the encoding for decoding responses (Node.js only)
responseEncoding: 'utf8', // default
// `xsrfCookieName` is the name of the cookie used for XSRF token
xsrfCookieName: 'XSRF-TOKEN', // default
// `xsrfHeaderName` is the HTTP header name for the XSRF token
xsrfHeaderName: 'X-XSRF-TOKEN', // default
// `onUploadProgress` handles upload progress events (browser only)
onUploadProgress: function (progressEvent) {
// Handle native progress event
},
// `onDownloadProgress` handles download progress events (browser only)
onDownloadProgress: function (progressEvent) {
// Handle native progress event
},
// `maxContentLength` defines the max response content size in bytes (Node.js)
maxContentLength: 2000,
// `maxBodyLength` defines the max request body size in bytes (Node.js)
maxBodyLength: 2000,
// `validateStatus` determines whether to resolve or reject based on HTTP status
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
// `maxRedirects` defines the max number of redirects in Node.js
maxRedirects: 5, // default
// `socketPath` specifies a UNIX socket for Node.js
socketPath: null, // default
// `httpAgent` and `httpsAgent` define custom agents for HTTP/HTTPS requests in Node.js
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// `proxy` defines the proxy server hostname, port, and protocol
proxy: {
protocol: 'https',
host: '127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'
}
},
// `cancelToken` for canceling requests
cancelToken: new CancelToken(function (cancel) {
}),
// `decompress` indicates whether to automatically decompress response body (Node.js only)
decompress: true // default
}Query Parameters and Request Body Data Handling
Query Parameters: Passed via the params property.
axios.get('/users', {
params: {
ID: 12345,
name: 'John'
}
});Request Body Data: For post, put, and patch methods, use the data property.
axios.post('/users', {
firstName: 'Fred',
lastName: 'Flintstone'
});Code Application Analysis
Example: GET Request
axios.get('https://api.example.com/users', {
params: {
ID: 12345,
name: 'John'
}
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});Example: POST Request
axios.post('https://api.example.com/users', {
firstName: 'John',
lastName: 'Doe'
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});Making Concurrent Requests
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
const [acct, perm] = await Promise.all([getUserAccount(), getUserPermissions()]);
// OR
Promise.all([getUserAccount(), getUserPermissions()])
.then(function ([acct, perm]) {
// ...
});Form Requests
// Multipart (multipart/form-data)
const {data} = await axios.post('https://httpbin.org/post', {
firstName: 'Fred',
lastName: 'Flintstone',
orders: [1, 2, 3],
photo: document.querySelector('#fileInput').files
}, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
// URL-encoded form (application/x-www-form-urlencoded)
const {data} = await axios.post('https://httpbin.org/post', {
firstName: 'Fred',
lastName: 'Flintstone',
orders: [1, 2, 3]
}, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});Example: Using Configuration Object
const config = {
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer YOUR_TOKEN'
},
timeout: 10000,
responseType: 'json',
validateStatus: true,
withCredentials: true
};
axios.get('https://api.example.com/data', config)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});Canceling Requests
You may need to cancel ongoing requests, such as when a component unmounts or a user navigates away. Axios provides request cancellation functionality.
Creating a Cancel Token:
import { CancelToken } from 'axios';
const source = CancelToken.source();
axios.get('/users', {
cancelToken: source.token
}).catch(thrown => {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// Handle error
}
});
// Cancel the request
source.cancel('Operation canceled by the user.');Error Handling
Ensure your application gracefully handles network errors and other exceptions. Use .catch() to capture and process errors, preventing crashes.
Error Handling Example:
axios.get('/users')
.then(response => {
console.log(response.data);
})
.catch(error => {
if (error.response) {
// Request made, but server responded with non-2xx status
console.error('Server responded with a status of:', error.response.status);
} else if (error.request) {
// Request made, but no response received
console.error('No response received:', error.request);
} else {
// Error occurred during request setup
console.error('Error setting up the request:', error.message);
}
console.error('Error config:', error.config);
});



