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.

99 lines
2.3 KiB

7 months ago
import Request from '@/js_sdk/luch-request/request.js'
import {
API_BASE_URL,
API_USER_URL,
} from '@/utils/appConfig.js';
7 months ago
const http = new Request()
http.setConfig((config) => {
/* 设置全局配置 */
7 months ago
config.baseUrl = API_BASE_URL /* 根域名不同 */
config.header = {
...config.header
}
return config
})
/**
* 自定义验证器如果返回true 则进入响应拦截器的响应成功函数(resolve)否则进入响应拦截器的响应错误函数(reject)
* @param { Number } statusCode - 请求响应体statusCode只读
* @return { Boolean } 如果为true, resolve, 否则 reject
*/
http.validateStatus = (statusCode) => {
return statusCode === 200
}
http.interceptor.request((config, cancel) => {
/* 请求之前拦截器 */
if (config.requestBase === 'USER') {
config.baseUrl = API_USER_URL
} else {
config.baseUrl = API_BASE_URL
}
7 months ago
const token = uni.getStorageSync('token');
if (token) {
7 months ago
config.header = {
'Authorization': token,
7 months ago
...config.header
}
} else {
7 months ago
config.header = {
...config.header
}
}
/*
if (!token) { // 如果token不存在调用cancel 会取消本次请求但是该函数的catch() 仍会执行
cancel('token 不存在') // 接收一个参数会传给catch((err) => {}) err.errMsg === 'token 不存在'
}
*/
return config
})
http.interceptor.response((response) => {
/* 请求之后拦截器 */
7 months ago
const res = response.data;
if (res.code !== 200) {
//提示错误信息
uni.showToast({
title: res.message,
duration: 1500,
icon: 'error'
7 months ago
})
//401未登录处理
if (res.code === 401) {
uni.showModal({
title: '提示',
content: '你已被登出,可以取消继续留在该页面,或者重新登录',
confirmText: '重新登录',
cancelText: '取消',
7 months ago
success: function(res) {
if (res.confirm) {
uni.navigateTo({
url: '/pages/public/login'
})
} else if (res.cancel) {
console.log('用户点击取消');
}
}
});
}
return Promise.reject(response);
} else {
return response.data;
}
}, (response) => {
//提示错误信息
console.log('response error', response);
uni.showToast({
title: response.errMsg,
duration: 1500
7 months ago
})
return Promise.reject(response);
})
export function request(options = {}) {
7 months ago
return http.request(options);
}
export default request