项目使用axios拦截器封装api

在api目录下新建一个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
import Qs from 'qs'
import axios from 'axios'
import store from '@/store'
import * as utils from '@/utils' //工具类
import { Toast } from 'mand-mobile'

const instance = axios.create({
baseURL: '', // 后端接口根目录
message: true
})

// 错误控制
const errorHandle = (status, message) => {
switch (status) {
case 401:
// store.dispatch('logout')
break
case 403:
break
case 404:
break
default:
Toast.failed(message)
}
}
// axios请求拦截器
/* 拦截器一般做什么?

    1. 修改请求头的一些配置项

    2. 给请求的过程添加一些请求的图标

    3. 给请求添加参数 */
instance
.interceptors
.request
.use(config => {
const token = utils.env !== 'dev' ? store.state.auth.token : ''
token && (config.headers.common.token = token)
if (config.method === 'post' && config.data) {
if (Object.prototype.toString.call(config.data) !== '[object FormData]') {
config.data = Qs.stringify(config.data)
}
config.headers.common['Content-Type'] = 'multipart/form-data'
}
return config
}, error => {
return Promise.reject(error)
})
// 响应拦截器,接受响应接口后的统一处理
instance
.interceptors
.response
.use(response => {
response.success = response.data.success
if (response.config.message) {
if (!response.success) {
response.data.message && Toast.failed(response.data.message)
} else {
response.config.method === 'post' && Toast.succeed(response.data.message || '操作成功')
}
}
return response
}, error => {
const { response } = error
response
? errorHandle(response.status, response.data.message || '网络连接失败,请稍后重试!')
: Toast.info('网络连接失败,请稍后重试!')
return Promise.reject(error)
})

export const createAPI = (url, method, params, config = {}) => {
if (method === 'get') {
config.params = params
} else {
config.data = params
}
return instance({
url,
method,
...config
})
}

export default instance

配置接口方式:
在api目录下新建个index.js
import { createAPI } from './http'

1
2
3
export default {
wxOuth: params => createAPI('/wechat/getOauthUrl', 'get', params)
}

最后在我们的vue组件中引入即可 import * as api from '@/api'
调用方式为: api.wxOuth(params).then(res=> {}).catch(err => {})