1. axios的二次封装
1 import axios from 'axios'
2 import qs from 'qs'
3
4 // 请求拦截
5 axios.interceptors.request.use(config => {
6 // 此处可以封装一些加载状态
7 return config
8 }, error => {
9 return Promise.reject(error)
10 })
11
12 // 响应拦截
13 axios.interceptors.response.use(response => {
14 return response
15 }, error => {
16 return Promise.resolve(error.response)
17 })
18
19 function checkStatus (response) {
20 // 此处可以封装一些加载状态
21 // 如果http状态码正常,则直接返回数据
22 if(response) {
23 if (response.status === 200 || response.status === 304) {
24 return response.data
25 // 如果不需要除了data之外的数据,可以直接 return response.data
26 } else if (response.status === 401) {
27 location.href = '/login';
28 } else {
29 throw response.data
30 }
31 } else {
32 throw {data:'网络错误'}
33 }
34
35 }
36
37 // axios默认参数配置
38 axios.defaults.baseURL = '/api/v0';
39 axios.defaults.timeout = 10000;
40
41 // restful API封装
42 export default {
43 post (url, data) {
44 return axios({
45 method: 'post',
46 url,
47 data: qs.stringify(data),
48 headers: {
49 'X-Requested-With': 'XMLHttpRequest',
50 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
51 }
52 }).then(
53 (res) => {
54 return checkStatus(res)
55 }
56 )
57 },
58 get (url, params) {
59 return axios({
60 method: 'get',
61 url,
62 params, // get 请求时带的参数
63 headers: {
64 'X-Requested-With': 'XMLHttpRequest'
65 }
66 }).then(
67 (res) => {
68 return checkStatus(res)
69 }
70 )
71 },
72 del (url, params) {
73 return axios({
74 method: 'delete',
75 url,
76 params, // get 请求时带的参数
77 headers: {
78 'X-Requested-With': 'XMLHttpRequest'
79 }
80 }).then(
81 (res) => {
82 return checkStatus(res)
83 }
84 )
85 }
86 }