【前端】纸掌柜h5端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

130 lines
3.0 KiB

import Http from './http.js'
import env from '@/env/index.js'
import { XAPPID } from '@/enums/index.js'
// 请求封装文件
const urlEnv = env === 'production' ? '' : `-${env}`
/**
* 系统默认的请求域名
*/
const baseUrl = `https://api-client-yyt${urlEnv}.qniao.cn`
// 请求url列表
const prefixList = {
// '/yyt-uec': `https://api-client-yyt${urlEnv}.qniao.cn`,
// '/base-paper-trading': `https://api-client-yyt${urlEnv}.qniao.cn`,
'/uec': `https://api-client-uec${urlEnv}.qniao.cn`
// '/document': `https://api-client-yyt${urlEnv}.qniao.cn`,
// '/cloud-print-user-center':`https://api-client-yyt${urlEnv}.qniao.cn`
}
const config = {
baseUrl: '',
header: {
'content-type': 'application/json;charset=UTF-8'
},
requestOption: {
// 是否需要隐藏loading
hideLoading: false,
// 是否返回原始数据
isReturnNativeResponse: false,
// 需要对返回数据进行处理
isTransformResponse: true
}
}
// 请求拦截
const reqInterceptor = (config, options) => {
const { url = '' } = config
// 添加token
let token = ''
try {
if (url.startsWith('uec')) {
token = uni.getStorageSync('uecToken')
} else {
token = uni.getStorageSync('qnToken')
}
} catch (e) {
console.error('获取缓存失败:', e)
}
config.header = {
...config.header,
Authorization: token || '',
'X-APP-ID': XAPPID
}
// 改变url
let newUrl = ''
if (url.startsWith('http')) {
newUrl = url
} else {
let hit = false
for (let key in prefixList) {
if (url.startsWith(key)) {
newUrl = prefixList[key] + url
hit = true
break
}
}
if (!hit) {
newUrl = baseUrl + url
}
}
config.url = newUrl
if (!options.hideLoading) {
uni.showLoading({
title: '加载中...'
})
}
return config
}
// 响应拦截
const resInterceptor = (response, options) => {
uni.hideLoading()
if (options.isReturnNativeResponse) {
return response
}
// 直接返回 {code,data,message}
if (!options.isTransformResponse) {
return response.data
}
const { statusCode } = response
const res = response.data
if (statusCode >= 200 && statusCode < 300) {
if (res.code == 0) {
// 将成功的null置位1
return res.data === null ? 1 : res.data
} else {
uni.showToast({
title: res.message,
icon: 'none'
})
return null
}
} else {
uni.showToast({
title: '服务器错误,请联系客服'
})
// 后期可以加记录
return null
}
}
const tranformConfig = (ins, config) => {
let conf = {
...config
}
conf.baseUrl = config.baseUrl || ins.baseUrl || ''
conf.header = config.header || ins.header
conf.method = config.method || 'GET'
conf.data = config.data || config.params || {}
conf.dataType = config.dataType || 'json'
conf.responseType = config.responseType || 'text'
return conf
}
const http = new Http(config, {
reqInterceptor,
resInterceptor,
tranformConfig
})
export default http