Axios封装

在工程化项目中对 axios 异步请求做一些封装可以方便使用,本文记录一种我习惯的 axios 封装及使用方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// service.js 创建 axios 实例,添加请求和响应拦截
const service = axios.create({
baseURL: ''
})
service.interceptors.request.use(
config => {
...
return config
},
err => {
return Promise.rject(err)
}
)
service.interceptors.response.use(
response => {
return response.data
},
err => {
return Promise.reject(err)
}
)
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
// useAxios.js 声明不同的 Method 方法
import service from './service'
const requese = (option) => {
const { url, method, params, data } = option
const staticParams = {} // 通用参数,如 uid 等
return service({
url,
method,
params: Object.assign(params || {}, staticParams),
data: Object.assign(data || {}, staticParams)
})
}
async function getFn (option) {
const res = await request({
method: 'GET',
...option
})
return res
}
async function postFn (option) {
const res = await request({
method: 'POST',
...option,
})
return res
}
async function deleteFn (option) {
const res = await request({
method: 'DELETE',
...option
})
return res
}
async function putFn (option) {
const res = await request({
method: 'PUT',
...option
})
return res
}

export const useAxios = () => {
return {
get: getFn,
post: postFn,
delete: deleteFn,
put: putFn
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// common.js 通用请求 api
import { useAxios } from './useAxios.js'
const request = useAxios()

export const function methodGet (url, params) {
return request.get({ url, params })
}
export const function methodPost (url, data) {
return request.post({ url, data })
}
export const function methodDelete (url, data) {
return request.delete({ url, data })
}
exoprt const function methodPut (url, data) {
return request.put({ url, data })
}
1
2
3
4
5
6
7
8
9
10
// 在组件中引入需要的请求方法使用
import { methodGet, methodPost } from '@/src/axios/common.js'

methodGet('api/xxx', {}).then(res => {
console.log(res)
})

methodPost('api/xxx', {}).then(res => {
console.log(res)
})