Axios工程化封装

Vue项目中封装

./utils/urls.js

1
2
3
4
5
const URLS = {
login = '/login'
}

export default URLS

urls.js 用来集中管理接口路径

./utils/http.js

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import axios from 'axios'
import store from '@/store/index'
import JSONBig from 'json-bigint'

/* axios 配置 */
var instance = axios.create({
/* 根路径 */
baseURL: 'http://192.168.31.34:8000/v1_0/',
/* 请求时限 */
timeout: 5000,
/* 处理响应数据 */
transformReponse: [function (data) {
try {
return JSONBig.parse(data)
} catch (error) {
return data
}
}]
})

/* 请求拦截器 */
instance.interceptors.request.use(
function (config) {
const { token } = store.state
/* 请求头添加token */
if (token) {
config.headers.Authorization = 'Bearer ' + token.token
}
return config
}, function (error) {
console.log(error)
return Promise.reject(error)
})

/* 响应拦截器 */
instance.interceptors.response.use(
function (response) {
return response.data
}, function (error) {
console.log(error)
return Promise.reject(error)
})

/**
* @param {String} method 请求的方法:get、post、delete、put、patch
* @param {String} url 请求的url:
* @param {Object} data 请求的参数
* @param {Object} headers 请求的数据格式
* @return {Promise} 返回一个promise对象,axios请求数据的返回值
*/

export default function (method, url, data = null, headers) {
method = method.toLowerCase()
if (method === 'post') {
return instance({
method: 'post',
url,
data,
headers: headers || { 'Content-Type': 'application/json' }
})
} else if (method === 'get') {
return instance({
method: 'get',
url,
params: data,
headers: headers || { 'Content-Type': 'application/x-www-form-urlencoded' }
})
} else if (method === 'delete') {
return instance({
method: 'delete',
url,
params: data,
headers: headers || { 'Content-Type': 'application/x-www-form-urlencoded' }
})
} else if (method === 'put') {
return instance({
method: 'put',
url,
data,
headers: headers || { 'Content-Type': 'application/json' }
})
} else if (method === 'patch') {
return instance({
method: 'patch',
url,
data,
headers: headers || { 'Content-Type': 'application/json' }
})
} else {
console.error('未知的method' + method)
return false
}
}

对 axios 的二次封装

./apis/login.js

1
2
3
4
5
import request from '@/utils/http'
import URLS from '@/utils/urls'

/* 登录接口 */
export const LOGIN = params => request('post', URLS.login, params)

在 apis 文件夹下创建 js 文件,封装请求接口

./apis/index.js

1
2
3
4
5
/* 导入各个模块的请求接口文件 */
import { LOGIN } from '@/apis/login'

/* 抛出这些接口 */
export const loginApi = LOGIN

将全部模块的请求接口文件全部导入在 index.js 中,在由 index.js 统一抛出接口

组件文件

1
2
3
4
5
6
7
8
9
10
11
12
<script>
import { loginApi } from '@/apis/index'

export default {
methods: {
async login () {
/* 接收参数 */
const res = await loginApi(this.loginData)
},
}
}
</script>

在组件中导入 ./apis/index.js 需要使用的接口