先加载axios
import axios from 'axios';
import Vue from 'vue';
import Qs from 'qs';
import urls from './url'
import {
Message
} from 'element-ui';
//用来设置接口请求频繁时候的调用
var api_url;
var api_data;
// axios.defaults.withCredentials = true; // 允许携带cookie
//路径
var baseURL = urls.host;
// 接口请求频繁时候的调用
function isObjectValueEqual(a, b) {
if (!a || !b) {
return true
}
var aProps = Object.getOwnPropertyNames(a)
var bProps = Object.getOwnPropertyNames(b)
if (aProps.length != bProps.length) {
return false
}
for (var i = 0; i < aProps.length; i++) {
var propName = aProps[i]
var propA = a[propName]
var propB = b[propName]
if (typeof propA === 'object') {
if (isObjectValueEqual(propA, propB)) {
return true
} else {
return false
}
} else if (propA !== propB) {
return false
} else {
isObjectValueEqual(propA, propB)
}
}
return true
}
const service = axios.create({
baseURL: baseURL,
})
// 设置请求拦截器
service.interceptors.request.use(
config => {
// 判断是否多次点击请求接口
if (api_url == config.url && isObjectValueEqual(api_data, config.params)) {
// alert("操作频繁")
console.log("操作频繁" + config.url)
return config;
}
api_url = config.url
api_data = config.params
setTimeout(() => {
api_url = "";
api_data = "";
}, 500)
// 参数转换为表单模式
var vm = new Vue()
// 设置请求头
config.headers = {
'Content-Type': 'multipart/form-data', // 模拟form表单方式提交请求
}
if (config.data) {
// var parmas = config.data
config.url = config.baseURL + config.url
if (parmas.type == 'json') {
config.headers = {
'Content-Type': 'application/json', // 模拟form表单方式提交请求
}
} else if (parmas.type == 'img') {
} else {
config.data = Qs.stringify(config.data)
}
}
if (config.params) {
if (config.params.submitType == 'form') {
config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
config.data = Qs.stringify(config.params)
}
}
return config
},
error => {
console.log(error) // for debug
Promise.reject(error)
}
)
// 设置响应拦截器
service.interceptors.response.use(
response => {
if (response.data.code == 200) {
return response.data;
} else {
Message.error(response.data.message);
//处理异常
return Promise.reject(response.data.msg)
}
},
error => {
var vm = new Vue();
Message.error("服务器内部异常");
// alert(error);
return Promise.reject(error)
}
)
export default service
接着对service进行整理改造
import service from './request'
class Https {
post(url,params){
return service({ url: url, method: 'post', params })
}
get(url,params){
return service({ url: url, method: 'get', params })
}
}
const https = new Https()
export default https
最后在main.js里引用并且生明
// 请求http
import https from '../api/http'
Vue.prototype.$http = https