huibing.xie | 1f1606f | 2018-08-20 15:46:55 +0800 | [diff] [blame] | 1 | import axios from 'axios' |
| 2 | import { Message, MessageBox } from 'element-ui' |
| 3 | import store from '../store' |
| 4 | import { getToken } from '@/utils/auth' |
| 5 | |
| 6 | // 网络请求约定属性名,不可在业务中使用 |
| 7 | const whitelist = ['X-Token', 'token', 'pageIndex', 'pageSize'] |
| 8 | // 创建axios实例 |
| 9 | const service = axios.create({ |
| 10 | baseURL: process.env.BASE_API, // api的base_url |
| 11 | timeout: 10000 // 请求超时时间 |
| 12 | }) |
| 13 | |
| 14 | // request拦截器 |
| 15 | service.interceptors.request.use(config => { |
| 16 | if (store.getters.token) { |
| 17 | config.headers['X-Token'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改 |
| 18 | } |
| 19 | if (config.params) { |
| 20 | for (const attr in config.params) { |
| 21 | if (whitelist.indexOf(attr) > -1) { |
| 22 | // 约定的属性不用转换 |
| 23 | continue |
| 24 | } |
| 25 | config.params[encodeURIComponent('mapBean[' + attr + ']')] = config.params[attr] |
| 26 | delete config.params[attr] |
| 27 | } |
| 28 | } |
| 29 | return config |
| 30 | }, error => { |
| 31 | // Do something with request error |
| 32 | console.log(error) // for debug |
| 33 | Promise.reject(error) |
| 34 | }) |
| 35 | |
| 36 | // respone拦截器 |
| 37 | service.interceptors.response.use( |
| 38 | response => { |
| 39 | /** |
| 40 | * code为非20000是抛错 可结合自己业务进行修改 |
| 41 | */ |
| 42 | const res = response.data |
| 43 | if (response.status !== 200) { |
| 44 | Message({ |
| 45 | message: res.message || '请求失败,状态码:' + res.code, |
| 46 | type: 'error', |
| 47 | duration: 5 * 1000 |
| 48 | }) |
| 49 | |
| 50 | // 50008:非法的token; 50012:其他客户端登录了; 50014:Token 过期了; |
| 51 | if (res.code === 50008 || res.code === 50012 || res.code === 50014) { |
| 52 | MessageBox.confirm('你已被登出,可以取消继续留在该页面,或者重新登录', '确定登出', { |
| 53 | confirmButtonText: '重新登录', |
| 54 | cancelButtonText: '取消', |
| 55 | type: 'warning' |
| 56 | }).then(() => { |
| 57 | store.dispatch('FedLogOut').then(() => { |
| 58 | location.reload()// 为了重新实例化vue-router对象 避免bug |
| 59 | }) |
| 60 | }) |
| 61 | } |
| 62 | return Promise.reject('error') |
| 63 | } else { |
| 64 | return response.data |
| 65 | } |
| 66 | }, |
| 67 | error => { |
| 68 | console.log('err' + error)// for debug |
| 69 | Message({ |
| 70 | message: error.message, |
| 71 | type: 'error', |
| 72 | duration: 5 * 1000 |
| 73 | }) |
| 74 | return Promise.reject(error) |
| 75 | } |
| 76 | ) |
| 77 | |
| 78 | export default service |