import Vue from './main'
import axios from 'axios'
import qs from 'qs'
import VueCookies from 'vue-cookies'
//POST传参序列化(添加请求拦截器)
axios.interceptors.request.use((config) => {
//在发送请求之前做某件事
var httpToken = VueCookies.get('mtoken');
config.timeout = 180000; //响应时间
config.headers.post['Content-Type'] = 'application/json;charset=UTF-8'; //配置请求头
config.headers.common['Authorization'] = 'OAuth '+ httpToken; //配置用户权限
if(config.method === 'post'){
config.data = qs.parse(config.data);
}
return config;
},(error) =>{
Vue.myVue.$message.warning({
showClose: true,
message: '加载超时',
type: 'warning'
});
return Promise.reject(error);
});
//返回状态判断(添加响应拦截器)
axios.interceptors.response.use((res) =>{
//对响应数据做些事
if(res.data.code && res.data.code != 200){
Vue.myVue.$message.warning({
showClose: true,
message: res.data.msg,
type: 'warning'
});
}
if(!res.data.success){
return Promise.resolve(res);
}
return res;
}, (error) => {
if(error.response.status == 401){
Vue.myVue.$message.error({
showClose: true,
message: '登录失效,请您重新登录!',
type: 'error'
});
Vue.myVue.$router.push('/');
}else{
Vue.myVue.$message.error({
showClose: true,
message: '系统开小差了,请稍后重试!',
type: 'error'
});
}
return Promise.reject(error);
});
//返回一个Promise(发送post请求)
export function fetchPost(url, params) {
return new Promise((resolve, reject) => {
axios.post(url, params)
.then(response => {
resolve(response);
}, err => {
reject(err);
})
.catch((error) => {
reject(error)
})
})
}
////返回一个Promise(发送get请求)
export function fetchGet(url, param) {
return new Promise((resolve, reject) => {
axios.get(url, {params: param})
.then(response => {
resolve(response)
}, err => {
reject(err)
})
.catch((error) => {
reject(error)
})
})
}
export default {
fetchPost,
fetchGet,
}
使用
在main.js中引入
import https from './https'
Vue.prototype.https = https;
在组件中调用
this.https.fetchPost('/v/merchant/budgetList',this.serchAccount).then((result) => {
if(result.data.code === 200){
}
}).catch((error) => {
})