| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- import Request from './request'
- import apiList from './api_list.js'
- import store from '@/store/index.js'
- import { setStorage, getStorage } from "@/util/index.js"
- export default function api(url, data = {}, showToast = true) {
- const request = new Request();
- let api = getApiObj(url);
- request.interceptor.request((config, cancel) => { /* 请求之前拦截器 */
-
- if (api.auth) {
- let token = getStorage('token');
- if (!token) {
- // store.dispatch('loginOut')
- throw ('暂未登录,已阻止此次API请求~');
- }
- }
- if (getStorage('openid')){
- config.header.openid = getStorage('openid')
- }
-
- if (getStorage('token')) {
- if(config.data.openid == null){
- delete config.data.openid
- config.data = { ...config.data}
- }else{
- config.data = { openid: getStorage('token'), ...config.data}
- }
-
- config.header.token = getStorage('token');
- }
-
- return config
- });
- request.interceptor.response((response) => { /* 请求之后拦截器 */
- if (response.data.code === 0) { // 服务端返回的状态码不等于200,则reject()
- if (showToast) {
- uni.showToast({
- title: response.data.msg || '请求出错,稍后重试',
- icon: 'none',
- duration: 2000,
- mask: true
- });
- }
- }
- if (response.data.code === 401) { // 服务端返回的状态码不等于200,则reject()
- uni.removeStorageSync('token');
- store.commit('LOGIN_TIP', true)
- }
- // if (response.config.custom.verification) { // 演示自定义参数的作用
- // return response.data
- // }
- return response
- }, (response) => { // 预留可以日志上报
- uni.showToast({
- title: '请求出错,稍后重试',
- icon: 'none',
- duration: 2000,
- mask: true
- });
- return response
- })
-
- return request.request({
- url: `${api.url}`,
- data,
- method: api.method
- })
- }
- function getApiObj(url) {
- let apiArray = url.split(".");
- let api = apiList;
- apiArray.forEach(v => {
- api = api[v];
- });
- return api;
- }
|