Axios自定义请求封装

Axios是Vue创作者尤雨溪推荐的契合Vue框架的http请求,本文以Element UI为例,介绍如何封装Axios自定义请求,并对请求做出统一的处理。

1首先安装Axios

1
npm install axios --save

2定义request.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
import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'

// create an axios instance
const service = axios.create({
baseURL: process.env.BASE_API, //process.env是Node的环境变量,这里定义了Axios请求的公用host,通过build和dev环境来区分
timeout: 300000 //接口最长等待时间
})

// request interceptor
service.interceptors.request.use(config => {
Do something before request is sent
if (store.getters.token) {
config.headers['Authorization'] = 'Bearer ' + store.getters.token // 让每个请求携带token
}
if (store.getters.language) {
config.headers['accept-language'] = store.getters.language
}
config.headers['Content-Type'] = 'application/json'
config.headers['withCredentials'] = true
return config
}, error => {
// Do something with request error
console.log(error) // for debug
return Promise.reject(error)
})

// respone interceptor
service.interceptors.response.use(
// response => response,
response => {
const res = response.data
if (res.code !== 20000) {
Message({
message: res.message,
type: 'error',
duration: 5 * 1000
})
// 50008:非法的token; 50012:其他客户端登录了; 50014:Token 过期了;
if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
store.dispatch("FedLogOut").then((result)=>{
Message.error('状态过期,请重新登录!')
setTimeout(() => {
location.reload() // 为了重新实例化vue-router对象 避免bug
}, 1000); //延迟一秒执行
}
return Promise.reject('error')
} else {
return response.data
}
},
error => {
console.log('err' + error) // for debug
Message.error(error.message)
return Promise.reject(error)
})

export default service

3定义api接口文件

import request from '@/utils/request'

export const getData = (params) => request({ url: '/xxx/xxx', method: 'get', params })

export const postData = (data) => request({ url: '/xxx/xxx', method: 'post', data })

4页面使用

import { getData } from '@/api/xxx'

...

const data={id:1}
getData(data).then((result) => {
    //success的回调
}).catch((err) => {
    //error的回调
})
扫一扫,请老师喝水