|
- import config from './config.js'
- import { clearAuth } from './auth.js'
- import { guid, getNonce, getVersion, getClient, isLoginTop } from './util.js'
-
- let BASE_URL = config.BASE_URL
- // #ifdef H5
- // H5 通过 manifest.json 的 devServer.proxy 代理到 /api,规避跨域
- BASE_URL = '/api'
- // #endif
-
- function clearLoginState() {
- clearAuth()
- // 动态引入避免和 Pinia store 形成循环依赖;storage 先同步清掉,页面状态随后刷新。
- import('@/store/user.js').then(({ useUserStore }) => {
- useUserStore().clear()
- }).catch(() => {})
- }
-
- function normalizeResponse(response) {
- // uni-app Promise 形式在部分端可能返回 [err, res],这里保留兼容;
- // 主流程已改用 success/fail callback,避免小程序端 response.data 解析不稳定。
- if (Array.isArray(response)) {
- const [err, res] = response
- if (err) throw err
- return res || {}
- }
- return response || {}
- }
-
- /**
- * 统一请求封装(沿用旧版鉴权约定)
- * - 自动附加 token / uid / mac / client / source / version 等公共参数
- * - 响应 code===0 视为成功;code===1009 登录失效,清空登录态并跳转登录
- * @param {{ url: string, method?: string, params?: object, headers?: object, loading?: boolean, authSilent?: boolean }} options
- */
- export default function request({
- url = '',
- method = 'GET',
- params = {},
- headers = {},
- loading = false,
- authSilent = false
- } = {}) {
- const fullUrl = BASE_URL + url
- const timestamp = parseInt(Date.now() / 1000)
- const token = uni.getStorageSync('token')
- const uid = uni.getStorageSync('open_id')
- let mac = uni.getStorageSync('mac')
- const source = uni.getStorageSync('source') || ''
-
- if (!mac) {
- const sysInfo = uni.getSystemInfoSync()
- mac = sysInfo.deviceId || guid()
- uni.setStorageSync('mac', mac)
- }
-
- const { timeStr, nonce } = getNonce()
- const { version, version_code } = getVersion()
-
- const header = Object.assign(
- {
- 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
- timestr: timeStr,
- nonce
- },
- headers
- )
- if (token) header.token = token
-
- let data = {
- token,
- uid,
- mac,
- base_timestamp: timestamp,
- client: getClient(),
- source,
- client_ios: uni.getSystemInfoSync().platform === 'ios' ? 1 : 0,
- version,
- version_code,
- ...params
- }
- // 去除空字符串字段
- Object.keys(data).forEach((k) => {
- if (data[k] === '') delete data[k]
- })
-
- if (loading) uni.showLoading({ mask: true, title: '加载中...' })
-
- return new Promise((resolve, reject) => {
- const finish = () => {
- if (loading) uni.hideLoading()
- }
-
- const handleResponse = (response) => {
- const normalized = normalizeResponse(response)
- const res = (normalized && normalized.data) || {}
- if (res.code === 0) {
- resolve(res)
- return
- }
- if (res.code === 1009) {
- clearLoginState()
- if (authSilent) {
- resolve({
- code: 0,
- data: { authExpired: true },
- list: [],
- msg: '',
- authExpired: true,
- raw: res
- })
- return
- }
- if (!isLoginTop()) {
- let loginUrl = '/pages/login/login'
- // #ifdef H5
- loginUrl += `?redirect=${encodeURIComponent(location.pathname + location.search)}`
- // #endif
- uni.navigateTo({ url: loginUrl })
- }
- reject(Object.assign({}, res, { authExpired: true }))
- return
- }
- reject(res)
- }
-
- uni.request({
- url: fullUrl,
- method,
- header,
- data,
- success: (response) => {
- try {
- handleResponse(response)
- } catch (e) {
- const status = e && e.statusCode
- reject({ code: 1, msg: status ? `网络异常 (${status})` : '网络异常,请重试!' })
- } finally {
- finish()
- }
- },
- fail: (e) => {
- const status = e && e.statusCode
- reject({ code: 1, msg: status ? `网络异常 (${status})` : '网络异常,请重试!' })
- finish()
- }
- })
- })
- }
|