import axios from 'axios' import utils from '@/utils/encode' import qs from 'qs' const service = axios.create({ // #ifndef MP baseURL: 'http://192.168.0.140:861', // #endif // #ifdef MP baseURL: 'http://192.168.0.140:861', // #endif timeout: 5000 }) let data = { params: '', serviceCode: '', digest: '', appkey: 'dirverAppAndroid' } service.interceptors.request.use( config => { // 拦截请求 console.log('发送请求', data) uni.showLoading({ title: '加载中...' }) const token = uni.getStorageSync('Authorization') config.headers['Authorization'] = token if (config.method === 'post' && config.url.indexOf('/weixin') < 0 && config.url.indexOf('/api') >= 0) { // 发送请求前,将参数加密,并生成密钥 data.serviceCode = config.data.serviceCode data.params = utils.encrypt(JSON.stringify(config.data)) data.digest = utils.md5Salt(JSON.stringify(config.data)) // console.log('参数:', data) config.data = qs.stringify(data) } if (config.method === 'post' && config.url.indexOf('/upload') >= 0) { // 上传图片前压缩图片 // compress() // console.log(data.params) // console.log('upload') } if (config.method === 'post' && config.url.indexOf('/weixin') >= 0) { // 上传图片前压缩图片 // compress() // console.log(data.params) // console.log('upload') config.baseURL = 'http://192.168.0.140:8089' } console.log('请求参数:', config) return config }, error => { uni.hideLoading() uni.showToast({ title: '请求失败!', icon: "none" }) return Promise.reject(error) } ) service.interceptors.response.use( response => { const res = response.data uni.hideLoading() if (res.code != '1000') { // 操作不成功,返回错误信息 if (res.code === 404) { // 直接跳转到首页 uni.reLaunch({ url: '/pages/index/index' }); } else if (res.code === 'TOKEN-9999') { // 登录过期,清除缓存 uni.removeStorageSync("Authorization") } else { uni.showToast({ title: res.msg, icon: "none" }) return Promise.reject(error) } } return res }, error => { uni.hideLoading() uni.showToast({ title: '请求失败!', icon: "none" }) return Promise.reject(error) } ) // #ifndef H5 service.defaults.adapter = function(config) { return new Promise((resolve, reject) => { var settle = require('axios/lib/core/settle'); var buildURL = require('axios/lib/helpers/buildURL'); var url = (config.url.indexOf('/weixin') < 0 && config.url.indexOf('/api') >= 0) ? (config.baseURL + buildURL( config.url, config.params, config.paramsSerializer)) : config.baseWxURL uni.request({ method: config.method.toUpperCase(), url: url, header: config.headers, data: config.data, dataType: config.dataType, responseType: config.responseType, sslVerify: config.sslVerify, complete: function complete(response) { response = { data: response.data, status: response.statusCode, errMsg: response.errMsg, header: response.header, config: config }; settle(resolve, reject, response); } }) }) } // #endif export default service