You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
cy_pda/common/http.interceptor.js

86 lines
2.0 KiB

/**
* Copyright (c) 2013-Now http://jeesite.com All rights reserved.
*/
import errorCode from "./errorCode";
// 此处第二个参数vm,就是我们在页面使用的this,你可以通过vm获取vuex等操作
const install = (Vue, vm) => {
// 通用请求头设定
const ajaxHeader = 'x-ajax';
const sessionIdHeader = 'Authorization';
const contentType = 'Content-Type';
// 请求参数默认配置
Vue.prototype.$u.http.setConfig({
baseUrl: vm.vuex_config.baseUrl,
originalData: true,
});
// 请求拦截,配置Token等参数
Vue.prototype.$u.http.interceptor.request = (req) => {
if (!req.header) {
req.header = [];
}
// 默认指定返回 JSON 数据
if (!req.header[ajaxHeader]) {
req.header[ajaxHeader] = 'json';
req.header[contentType] = 'application/json'
}
// 设定传递 Token 认证参数
if (!req.header[sessionIdHeader] && vm.vuex_token) {
req.header[sessionIdHeader] = vm.vuex_token;
}
return req;
}
// 响应拦截,判断状态码是否通过
Vue.prototype.$u.http.interceptor.response = async (res, req) => {
const code = res.data.code;
const message = res.data.msg;
// token过期,重新登录
if (code === 401) {
vm.$u.toast('身份过期,请重新登录');
// vm.$u.api.logout().then(res => {
//清空存储信息
vm.$u.vuex('vuex_token', '')
vm.$u.vuex('vuex_user', {})
vm.$u.vuex('vuex_code', '')
setTimeout(() => {
uni.reLaunch({
url: "/pages/login/login",
});
}, 500);
// });
return
}
if (code !== 200) {
vm.$u.toast(message);
return Promise.reject(new Error(message))
}
return res.data;
}
// 封装 post json 请求
vm.$u.postJson = (url, data = {}, header = {}) => {
header['content-type'] = 'application/json';
return vm.$u.http.request({
url,
method: 'POST',
data
})
}
}
export default {
install
}