//http.js
import Vue from 'vue'
import axios from "axios"
const Axios = axios.create({
timeout: 30000,
//responseType:"json",
withCredentials:false,
});
/**
axios访问前的拦截,增加配置信息
baseURL=反向代理的URL地址,配置在nginx、apache下有效,tomcat下请配置为/
data=将json转换为字符发送
headers = 设置HTTP头文件,其中token是登陆时从服务器获取的
withCredentials = 提交时是否携带cookie
*/
Axios.interceptors.request.use(
config => {
var token = sessionStorage.getItem("account.token") || "";
if (token && token != "") {
config.headers = {
"Authorization": 'Bearer ' + token,
'Content-Type':'application/json; charset=utf-8',
}
}else{
config.headers = {
'Content-Type':'application/x-www-form-urlencoded; charset=utf-8',
}
config.data = Vue.prototype.qs.stringify(config.data)
}
return config;
},
error => {
return Promise.reject(error);
}
);
/**
axios响应时拦截处理
*/
httpService.interceptors.response.use(
response => {
let msg = ""
if (response.status == 200) {
switch (response.data.code) {
case 1000:
msg = response.data.msg
// Message['success']({
// background: true,
// content: msg,
// duration: 3
// })
break;
default:
msg = response.data.msg
Message['error']({
background: true,
content: msg,
duration: 10,
closable: true
})
}
// 统一处理状态
return Promise.resolve(response.data.data)
} else {
return Promise.reject(response)
}
},
// 处理处理
error => {
if (error && error.response) {
switch (error.response.status) {
case 400:
error.message = '错误请求';
break;
case 401:
error.message = '未授权,请重新登录';
break;
case 403:
error.message = '拒绝访问';
break;
case 404:
error.message = '请求错误,未找到该资源';
break;
case 500:
error.message = '服务器端出错';
break;
default:
error.message = `未知错误${error.response.status}`;
}
Message['error']({
background: true,
content: error.message,
duration: 10,
closable: true
})
} else {
error.message = "连接到服务器失败";
Message['error']({
background: true,
content: error.message,
duration: 10,
closable: true
})
}
return Promise.reject(error);
}
)
/**
* 封装get方法
* @param url
* @param data
* @returns {Promise}
*/
const get = function (url, param = {}) {
return new Promise((resolve, reject) => {
Axios.get(url, {
params: JSON.stringify(param),
})
.then(response => {
resolve(response.data);
})
.catch(err => {
resolve({
code: "no",
msg: err.err
});
//reject(err)
})
})
}
const post = function (url, param = {}, bURL=Vue.prototype.config.proxy) {
let config = {
baseURL:bURL
}
return new Promise((resolve, reject) => {
Axios.post(url, param, config).then(response => {
resolve(response.data);
}).catch(err => {
var t = err.err.response.data
resolve(t);
})
})
}
export default {
install: function (Vue, Option) {
Object.defineProperty(Vue.prototype, "$http", {
value: Axios
});
Object.defineProperty(Vue.prototype, "$get", {
value: get
});
Object.defineProperty(Vue.prototype, "$post", {
value: post
});
}
};
然后在main.js中引入:
import axios from '@/assets/js/http.js'
Vue.use(axios);
在项目中使用:
this.$post(this.api.organize.list, p).then((res) => {});
网友评论