123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157 |
- // 封装请求
- import config from './config.js'
- import store from '@/store'
- import {
- getToken
- } from "./common.js"
- // 请求域名
- const baseUrl = process.env.NODE_ENV === 'development' ? config.devBaseUrl : config.proBaseUrl
- // const baseUrl = config.baseUrl
- let LoginFailure = false
- // 存储请求信息,当接口正在请求中,不会进行下一次接口请求
- const pending = {}
- // 处理请求成功
- const isHttpSuccess = (stauts) => {
- return stauts >= 200 && stauts < 300
- }
- // 处理请求错误
- const errorHandle = (res) => {
- // 日志处理 全局错误提示
- if (res && res.statusCode !== 200) {
- // 浏览器错误
- uni.showToast({
- title: '系统错误,请联系管理员',
- icon: 'none',
- duration: 2000
- })
- } else {
- // console.log('errorHandle1', res)
- // 服务器错误
- uni.showToast({
- title: res.data.msg || '系统错误,请联系管理员',
- icon: 'none',
- duration: 2000
- })
- }
- }
- export const request = async (opt = {}) => {
- // 考虑与uniapp的接口进行兼容
- let headers = {
- "Content-Type": "application/x-www-form-urlencoded"
- }
- const token = getToken();
- if (token) {
- headers['authorization'] = token;
- }
-
- const {
- data,
- success,
- fail
- } = opt
- // pending 中的键名
- const key = opt.url + '&' + (opt.method || 'GET')
- // 处理请求地址
- opt.url = baseUrl + opt.url
- // 处理公共参数
- opt.data = data
- opt.timeout = 5000 // 请求超时时间
- opt.header = headers
-
- const result = new Promise((resolve, reject) => {
- const handler = uni.request(Object.assign({}, opt, {
- success: (res) => {
- const data = res.data;
- delete pending[key]
- if (data.type === 'ok') {
- resolve(data.message)
- }else if (data.type === '999') {
- if(!LoginFailure){
- LoginFailure = true
- // 未登录
- store.commit('app/SET_TOKEN' , '');
- uni.reLaunch({
- url:'/pages/login/index',
- complete:() => {
- LoginFailure = false
- }
- })
- }
-
- } else {
- uni.showToast({
- icon: 'none',
- title: data.message || '系统错误'
- })
- reject(data)
- }
- },
- fail: (e) => {
- // uni.showToast({
- // icon: 'none',
- // title: '系统错误'
- // })
- reject()
- },
- complete: () => {
- setTimeout(() => {
- uni.hideLoading()
- },1000)
- }
- }))
- if (pending[key]) {
- // 中断请求
- pending[key].abort()
- }
- // setTimeout 让pending[key].abort()执行完成后在存值
- setTimeout(() => {
- pending[key] = handler
- }, 0)
- })
- return result
- }
- export const axios = {
- get(url, data, options = {}) {
- return request({
- url,
- data,
- method: 'GET',
- ...options
- })
- },
- post(url, data, options = {}) {
- return request({
- url,
- data,
- method: 'POST',
- ...options
- })
- },
- getDow(url, data, options = {}) {
- // console.log('getDow' , options)
- return request({
- url,
- data,
- method: 'GET',
- ...options
- })
- },
- }
|