// 配置API接口地址与服务器静态文件地址
var root = 'http://192.168.1.108:8082';
// 引用axios
var axios = require('axios')
var qs = require('qs')
axios.defaults.headers.post['Content-Type'] = 'application/json'
//全局封装错误处理函数
axios.interceptors.request.use(
config => {
config.headers = {
//请求头自定义
'Content-Type': 'application/json',
//jwt为与后端协定好的特殊请求头
'jwt':window.localStorage.getItem('jwt')
};
// 在post请求发送出去之前,对其进行编码
// if (config.method === 'post') {
// config.data = qs.stringify(config.data);
// }
return config;
},
err => {
return Promise.reject(err);
});
// http response 拦截器
axios.interceptors.response.use(
response => {
// console.log(response);
//拦截请求判断jwt后做业务所需相应操作
if(response.headers.jwt !== false && response.headers.jwt !== null && response.headers.jwt !== undefined && response.headers.jwt !== ''){
let jwt = response.headers.jwt;
window.localStorage.removeItem('jwt');
window.localStorage.setItem('jwt',jwt);
};
//10003为登录状态失效,失效状态下返回登录路由
if(response.data.status == 10003){
window.location.href="/login";
};
return response;
},
error => {
if (error.response) {
console.log("请求错误", error.response.status);
switch (error.response.status) {
case 401:
// store.dispatch('logout');
console.log("401");
break;
case 404:
console.log('接口不存在');
break;
case 500:
console.log('服务器错误');
}
}
return Promise.reject(error);// 返回接口返回的错误信息
});
function getdata(method, url, params, success, failure) {
axios({
method: method,
url: url,
data: method === 'POST' || method === 'PUT' ? params : null,
params: method === 'GET' || method === 'DELETE' ? params : null,
baseURL: root,
withCredentials: true, //跨域请求凭证验证。
timeout: 30000
})
.then(function (res) {
success(res.data);
})
.catch(function (err) {
let res = err.response
if (err) {
return
}
})
}
// 返回在vue模板中的调用接口
export default {
get: function (url, params, success, failure) {
return getdata('GET', url, params, success, failure)
},
post: function (url, params, success, failure) {
return getdata('POST', url, params, success, failure)
},
put: function (url, params, success, failure) {
return getdata('PUT', url, params, success, failure)
},
delete: function (url, params, success, failure) {
return getdata('DELETE', url, params, success, failure)
},
root: root
}
然后在main.js中引入此封装文件
import api from './api/http'
之后可在需要的地方调用
this.$api.get(
//接口url
"/url",
//传输参数
this.search,
response => {
//回调
},
err=> {
//失败回调
}
);