📝 Edit page
➕ Add page
Axios
Install
$ npm install axios
Import
import axios from "axios";
Usage
Async
try {
const resp = await axios.get(url);
console.log(resp);
} catch(err) {
console.error(err);
}
In an async function.
async function getUser() {
try {
const resp = await axios.get('/user?ID=12345');
console.log(resp);
} catch(err) {
console.error(err);
}
}
Promises
axios.get('/users')
.then(resp => {
console.log(resp.data);
});
Params
axios.get('/user?ID=12345')
// OR
const params = {
ID: 12345
}
axios.get('/user', { params })
POST request
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
More advanced. Note Axios includes automatic JSON and form-encoded serialization and parsing.
const query = new URLSearchParams(query).toString();
const url = '/myendpoint'
const options = {
params: query,
body
};
const resp = await axios.post(
url,
options
);
Concurrent requests
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
const requests = [getUserAccount(), getUserPermissions()]
Promise.all(requests)
.then(function (results) {
const [account, permissions] = results;
// OR
const account = results[0];
const permissions = results[1];
});