123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117 |
- import Request from './request';
- import apiList from './api.js'
- const shoproRequest = new Request();
- export default function http(url,
- data = {},
- toastBefore = '', // 请求前加载提示
- toastAfter = true, // 请求后错误提示
- ) {
- let api = getApiPath(url);
- /* 请求之前拦截器 */
- shoproRequest.interceptor.request((config, cancel) => {
- let token = uni.getStorageSync('token') || "";
- if (api.auth && !token) {
- uni.hideLoading();
- uni.showLoading({
- title: '暂未登录,请先登录',
- icon: 'none',
- duration: 2000,
- });
- uni.redirectTo({
- url: '/subpkg/pages/login/index',
- success: function(res) {}
- });
- throw (`暂未登录,已阻止此次API请求: '${api.url}'`);
- }
- token && shoproRequest.setConfig(config => {
- config.header.Authorization = token
- })
- if (toastBefore !== '') {
- uni.showLoading({
- title: toastBefore,
- mask: true
- });
- }
- return config
- });
- /* 请求之后拦截器 */
- shoproRequest.interceptor.response((response) => {
- uni.hideLoading();
- if (response.code != 0 || response.success === false) {
- if (toastAfter) {
- uni.showToast({
- title: response.message || '请求出错,稍后重试',
- icon: 'none',
- duration: 2000,
- mask: true
- });
- }
- // token过期注销
- if (response.code === 161099) {
- if (response.message == '当前登录已失效,请重新登录') {
- uni.showToast({
- title: response.message,
- icon: 'none',
- duration: 2000
- });
- uni.removeStorageSync('token');
- } else {
- uni.showToast({
- title: response.message,
- icon: 'none',
- });
- }
- throw (`登录已过期或注销,已阻止请求: '${api.url}'`);
- }
- }
- return response
- })
- let userType = uni.getStorageSync('userType') || "drug";
- const userPrefix = {
- mcs: "/mcs",
- drug: "/drug"
- }
- return shoproRequest.request({
- url: userPrefix[userType] + typeUrl(api),
- data,
- method: api.method
- })
- }
- function typeUrl(api) {
- let tUrl = null;
- let userType = uni.getStorageSync('userType') || "drug";
- if (api.url) {
- tUrl = api.url;
- } else {
- if (userType === 'mcs') {
- tUrl = api.mcsurl;
- }
- if (userType === 'drug') {
- tUrl = api.durgurl;
- }
- }
- return tUrl;
- }
- // 组装接口路径
- function getApiPath(url) {
- let api;
- let apiArray = url.split(".");
- if (apiArray.length == 1) {
- api = {
- auth: true,
- method: "POST",
- url: url,
- }
- } else {
- api = apiList;
- apiArray.forEach(v => {
- api = api[v];
- });
- }
- return api;
- }
|