asd/asd-pc/common/api/request.js

71 lines
1.9 KiB
JavaScript
Raw Normal View History

2024-11-21 11:06:22 +08:00
import {
baseUrl
} from "@/common/utils/config.js" //请求根路径(服务器地址)
import store from '@/common/store/index.js'
import Vue from "vue"
import Common from '@/common/utils/common.js'
// process.env.NODE_ENV === 'development' ? 'http://192.168**:6002' : 'http://***/api'; //环境配置
//向外暴露一个方法,传入一个空对象
export function service(options = {}, contentType) {
options.url = `${baseUrl}${options.url}`; //前面为你的服务器地址,后面为具体接口地址
//配置请求头
options.header = {
'content-type': contentType ? contentType : "application/json", //默认请求头,可不写
'Authorization': store.getters.token //Bearer ,你请求数据需要的自定义请求头(令牌)
};
// 创建promise
return new Promise((resolved, rejected) => {
//成功
options.success = (res) => {
2024-11-21 11:32:11 +08:00
console.log(20,err)
2024-11-21 11:06:22 +08:00
if (res.data.code === 401) {
2024-11-21 11:32:11 +08:00
store.commit('setPropName', {
propName: 'TOKEN',
value: ""
})
2024-11-21 11:06:22 +08:00
uni.navigateTo({
url: '/loginPackage/pages/Login'
})
}
console.log(20,res);
if (Number(res.data.code) == 200||res.data.paySign||res.data.isPay) { //请求成功
resolved(res.data); //请求成功时返回接口数据
} else {
uni.showToast({
icon: 'none',
duration: 3000,
2024-11-21 11:32:11 +08:00
title: res.data.msg
2024-11-21 11:06:22 +08:00
});
2024-11-21 11:32:11 +08:00
if (res.data.msg == "Token失效请重新登录!") {
2024-11-21 11:06:22 +08:00
store.commit("logout");
setTimeout(() => {
uni.navigateTo({
url: '/loginPackage/pages/Login'
})
}, 1500)
}
rejected(res); //请求失败时返回错误信息
}
}
2024-11-21 11:32:11 +08:00
//错误
2024-11-21 11:06:22 +08:00
options.fail = (err) => {
2024-11-21 11:32:11 +08:00
store.commit('setPropName', {
propName: 'TOKEN',
value: ""
})
if (res.data.code === 401) {
uni.navigateTo({
url: '/loginPackage/pages/Login'
})
}
rejected(err); //请求失败时返回错误信息
2024-11-21 11:06:22 +08:00
}
console.log(options);
uni.request(options); //传入配置好的对象
});
}