123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- /**
- * 网络请求
- * @author yxk
- */
- import App from '../main.js'
- import { BASE_URL_FN } from '../config.js'
- let loadingCount = 0
- const closeLoading = () => {
- if (loadingCount <= 0) {
- loadingCount = 0
- uni.hideLoading();
- }
- }
- const service = (config) => {
- if (!config.hideLoading && loadingCount === 0) {
- uni.showLoading({
- mask: true,
- title: '加载中'
- })
- }
- loadingCount++
- if (!config.header) {
- config.header = {}
- }
- if (config.requestType === 'form') {
- config.header = {
- ...config.header,
- 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
- }
- }
- const token = uni.getStorageSync('token') || null
- const flag = config.hasOwnProperty('requiredAuth') ? !!config.requiredAuth : true
- if (token) {
- config.header = {
- ...config.header,
- 'Admin-Token': token
- }
- } else if (flag) {
- // 非登录相关接口,没有 token 直接转到登录页
- loadingCount = 0
- uni.hideLoading()
- App.$Router.reLaunch('/pages_login/index')
- return Promise.reject()
- }
- let url = ''
- if (!config.url.startsWith('http')) {
- url = BASE_URL_FN() + config.url
- } else {
- url = config.url
- }
- const appid = uni.getStorageSync('appid') || null
- if (appid) {
- config.header.k = appid
- }
- // #ifdef H5
- config.withCredentials = true
- // #endif
- return new Promise((resolve, reject) => {
- uni.request({
- ...config,
- url,
- success: res => {
- loadingCount--
- closeLoading()
- const data = res.data
- if (config.responseType === 'arraybuffer') {
- resolve(res)
- return
- }
- if (data.code === 302) {
- App.$Router.reLaunch('/pages/login/index')
- let str = ''
- if (data.extra && data.extra === 1) {
- str = `您的账号${data.extraTime}在别处登录。如非本人操作,则密码可能已泄漏,建议修改密码`
- } else {
- str = '登录已失效,请重新登录'
- }
- setTimeout(() => {
- App.$toast(str)
- str = null
- }, 500)
- reject('登录已失效,请重新登录')
- return
- }
- if (data.code === 0 || data.code === 200) {
- if (data.hasOwnProperty('data')) {
- resolve(data.data)
- } else {
- resolve(data)
- }
- } else {
- App.$toast(data.msg)
- reject(data.msg)
- }
- },
- fail: error => {
- loadingCount--
- closeLoading()
- reject(error)
- }
- })
- })
- }
- export default service
|