0%

Birthday again & notes about axios

Well, after 3 rounds Ben Ming Nian plus this horrible 2020 which seems to have no sign to getting better, birthday comes again.

Used to set ambitious goals at the beginning of new year, and failed to achieve none of them. Surprisingly I managed to get one small goal done - now I have been keeping training for 21 days in a row, at least 60 mins everyday.

Many Chinese foreign students flee away from UK, USA, and other places from all over the world back to their hometown. Feel little jealous for them.

For couple of weeks ago, I started one Udemy course which I have bought for quite a while, and in the last project - which I have not finished yet, just get bable, webpack, npm etc part done - I get know little about axios, so decide to take some notes here.

Q: What is axios

A:
Axios is a modern JavaScript library built on top of XMLHttpRequest for making AJAX calls.
REACT/VUE officially recommend to use axios to make AJAX requests
Documentation: github.com/axios/axios

Q: Features

A:
Make XMLHttpRequests from the browser
Make http requests from node.js
Supports the Promise API
Intercept request and response
Transform request and response data
Cancel requests
Automatic transforms for JSON data
Client side support for protecting against XSRF

Create instance

1
2
3
4
5
6
7
8
import axios from "axios";
let config = {
baseURL: "host address",
timeout: 5000,
headers: { "X-Custom-Header": "foobar" }
};

export default axios.create(config);

Create instance

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
let axiosObj = axios.create();

// axios setting
axiosObj.defaults.timeout = 5000;
let axiosDate;
// http request intercepter
axiosObj.interceptors.request.use(config => {
config.withCredentials = true; // CORS check if takes cookie
if (store.state.token) {
config.headers.Authorization = `token ${store.state.token}`;
}

if (
(config.data && config.data.loading === "false") ||
(config.params && config.params.loading === "false") ||
config.loading === "false"
) {
} else {
axiosDate = new Date();
store.dispatch("LOADING", true);
}
const axiosConfig = 1 ? fn(config) : config;
});

const fn = config => {
let accept = config.headers.common["Accept"];
if (accept == null) {
accept = "*/*";
config.headers["Accept"] = accept;
}
let date = config.headers["date"];
if (date == null) {
date = "";
}
let contentType = config.headers["contentType"];
if (contentType == null) {
contentType = "";
}
let { method, url, params } = config;
config.headers["X-x"] = "x";
config.headers["X-x"] = "x";
return config;
};

Change axios's setting

1
2
3
4
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";

Instance default setting

1
2
3
4
5
6
7
// change setting when create instance
var instance = axios.create({
baseURL: "https://api.example.com"
});

// change setting after instance was created
instance.defaults.headers.common["Authorization"] = AUTH_TOKEN;

Available instance methods, additional declared configuration will be merged with instance configuration

1
2
3
4
5
6
7
8
axios#request(config)
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]])

Config's priority, request config > instance.defaults > default

1
2
3
4
5
6
7
8
9
10
// create an instance, and now timeout = 0 as default
var instance = axios.create();

// instance.defaults set timeout = 2500 ms, which has higher priority than default
instance.defaults.timeout = 2500;

// request config reset timeout = 5s,and its priority is highest
instance.get("/longRequest", {
timeout: 5000
});

Other config

1
2
3
4
5
6
// `auth': HTTP is used as basic authentication scheme
// set one `Authorization' header to overwrite any existing `Authorization' Custom-Header to use `headers` config
auth: {
username: 'janedoe',
password: 's00pers3cret'
},

Usage

1
2
3
4
5
import axios from "./axios.js";

export const getData = () => {
return axios.get("url");
};

Examples
axios intercepters