Vue封装axios
import axios from 'axios'; import { Message } from 'element-ui'; import store from '@/store'; import config from '@/config'; // import { stringifyParms } from '@/utils/core'
//form表单格式转换 不需要form表单格式(application/x-www-form-urlencoded)需要删除此方法。
stringifyParms(params){
return Object.keys(params).sort().map(key => key + '=' + params[key]).join('&')
}
class Service { baseConfig = { baseURL: config.apiURL, headers: {}, timeout: 8000 } // axios实例 instance = null constructor() { const token = store.getters.token; if (token) { this.setHeader({ Authorization: store.getters.tokenType + ' ' + token }) } else { this.initInstance(); } } // 设置请求头 setHeader = (headers) => { this.baseConfig.headers = { ...this.baseConfig.headers, ...headers }; this.initInstance(); } // get请求 get = (url, data = {}, config = {}) => this.instance({ ...{ url, method: 'get', params: data }, ...config }) // post请求 post = (url, data = {}, config = {}) => this.instance({ ...{ url, method: 'post', data:stringifyParms(data) }, ...config }) // 不经过统一的axios实例的post请求 postOnly = (url, data = {}, config = {}) => axios({ ...this.baseConfig, ...{ url, method: 'post', data }, ...config }) // 不经过统一的axios实例的get请求 getOnly = (url, data = {}, config = {}) => axios({ ...this.baseConfig, ...{ url, method: 'get', params: data }, ...config }) // delete请求 deleteBody = (url, data = {}, config = {}) => this.instance({ ...{ url, method: 'delete', data }, ...config }) deleteParam = (url, data = {}, config = {}) => this.instance({ ...{ url, method: 'delete', params: data }, ...config }) initInstance() { this.instance = axios.create(this.baseConfig); this.setReqInterceptors(); this.setResnterceptors(); } // 请求拦截器 setReqInterceptors = () => { this.instance.interceptors.request.use( config => { return config; }, err => { Message({ type: 'error', message: '请求失败', showClose: true, }) return Promise.reject(err); }) } // 响应拦截器 setResnterceptors = () => { this.instance.interceptors.response.use( res => { const { status, data, msg } = res.data; if (status === "0") { return data; } else { Message({ type: 'error', message: msg || '获取数据失败', showClose: true, }) return Promise.reject(res); } }, err => { Message({ type: 'error', message: '服务器响应失败', showClose: true, }) return Promise.reject(err); } ); } } export default new Service();
使用:
import service from '@/request/service'; // 登录 export const login = (data) => service.post('/login', data);