1. Installing axios
Install with npm
1
| npm install axios --save
|
There are two ways to register it globally:
- Bind it to the prototype
1
2
| import axios from "axios";
Vue.prototype.axios = axios;
|
With this approach, every Vue object gets a new axios object.
1
2
3
| this.axios.post(apiUrl).then((res) => {
//do something
});
|
- Mount it on the windows object
Anywhere in the DOM, you can use the axios function.
1
2
| import axios from "axios";
window.axios = axios;
|
1
2
3
| axios.post(apiUrl).then((res) => {
//do something
});
|
2. Configuring axios
To work with Django’s CSRF validation, you need to configure axios.
1
2
3
4
| var axiosDefaults = require("axios/lib/defaults");
axiosDefaults.xsrfCookieName = "csrftoken";
axiosDefaults.xsrfHeaderName = "X-CSRFToken";
axiosDefaults.withCredentials = true;
|
3. axios interceptors
Interceptors let you apply common handling to requests, such as exceptions and the format of returned data.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| axios.interceptors.response.use(
(response) => {
return response;
},
(error) => {
if (error.response) {
switch (error.response.status) {
case 500:
// do something
break;
case 402:
// do something
break;
}
}
return Promise.reject(error.response.data); // 返回接口返回的错误信息
},
);
|
4. Passing parameters with axios
4.1 GET requests
1
2
3
4
5
6
| let params = {
key1: "value1",
key2: "value2",
};
axios.get(apiUrl, { params });
//数据编码形式: /?key1=value1&key2=value2
|
4.2 POST requests with x-www-form-urlencoded
By default axios serializes a javascript object into JSON. To send data in application/x-www-form-urlencoded format:
1
2
3
4
5
| let params = new URLSearchParams();
params.append("key1", "value1");
params.append("key2", "value2");
axios.post(apiUrl, params);
//数据编码形式:key1=value1&key2=value2
|
1
2
3
4
5
6
7
| let qs = require("qs");
let params = {
key1: "value1",
key2: "value2",
};
axios.post(apiUrl, qs.stringify(params));
//数据编码形式:key1=value1&key2=value2
|
1
2
3
4
5
6
7
8
9
10
11
12
13
| import qs from "qs";
let data = {
key1: "value1",
key2: "value2",
};
let options = {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
data: qs.stringify(data),
url: apiUrl,
};
axios(options);
// 数据编码形式: key1=value1&key2=value2
|
1
2
3
4
5
6
7
8
9
10
11
12
| axios.post(
apiUrl,
{
key1: "value1",
key2: "value2",
},
{
headers: {
"Content-Type": "multipart/form-data",
},
},
);
|
4.4 request payload
1
2
3
4
| let formData = new FormData();
formData.append("key1", "value1");
formData.append("key2", "value2");
axios.post(apiUrl, formData);
|
5. Django’s backend cannot distinguish ajax from non-ajax
Looking at the django/http/request.py source file, you can see that Django distinguishes Ajax requests by a marker in the request headers.
1
2
| def is_ajax(self):
return self.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
|
How to handle it with axios
1
2
3
| axiosDefaults.headers.common = {
"X-Requested-With": "XMLHttpRequest",
};
|
6. References