赞
踩
封装axios,使用了ES6语法
import axios from 'axios' class XHR { constructor(config) { this.config = { // baseURL: 'https://www.fastmock.site/mock/c17a53c1e9a5235f42f6af1f21fab7c2/traffic', // mock接口 baseURL: 'https://bc.yncgj.cn:10009//bcz/api/', // 线上服务器地址 // baseURL: 'http://192.168.2.49:10920/bcz/api/', // 本地调试地址 headers: {}, crossDomain: true } // 初始化 请求实例 this.config = Object.assign(this.config, config) this.$request = axios.create(this.config); //请求拦截器 this.$request.interceptors.request.use( config => { config.withCredentials = false; // console.log(sessionStorage.getItem('toKen')); if (sessionStorage.getItem('toKen')) { config.headers.Authorization = sessionStorage.getItem('toKen') + ''; } return config; }, error => { return Promise.reject(error); }); } get(url, data) { return this.request(url, data, 'GET') } post(url, data, config = {}) { return this.request(url, data, 'POST', config) } request(url, data, method = 'GET', option) { // debugger // 格式化参数 if (typeof data === 'string') { method = data data = {} } const config = { url, method } // 区分 post get if (method === 'GET') { config.params = data config.data = qs.stringify(data) } else { config.data = data } // 发起请求 return this.$request(config).then(({ data }) => { const result = { code: parseInt(data.code || 0), count: parseInt(data.count || 0), data: data.data, msg: data.message, } return result }).catch((error) => { error = error && error.toString() console.error('接口调用异常: error', error) if (error && (error.includes('Error:') || error.includes('<html'))) { error = '接口异常,请联系管理员!' } return Promise.reject(error) }) } } export default XHR
封装接口
import XHR from './xhr' const req = new XHR() export default { /** * 登录 */ signIn: params => req.get(`/toLogin`, params), /** * 设施大类 */ equipment: params => req.get(`/facilityType/queryFacilityTypeParentList`, params), /** * 提交表单 */ submitForm: params => req.post(`/facility/save`, params), /** * 上传 */ upLoad: params => req.post(`/facility/uploadBatch`, params), }
挂在到全局,mian.js中
import allRequertAjax from "./API/interface";
Vue.prototype.$http = allRequertAjax;
使用
async getEquipment() {
try {
const { data } = await this.$http.equipment();
this.list = data;
} catch(error) {}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。