| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117 |
- /**
- * 网络请求封装
- */
- // 固定的 clientid
- const CLIENT_ID = '2f847927afb2b3ebeefc870c13d623f2'
- // 基础 URL(根据实际情况修改)
- const BASE_URL = 'http://127.0.0.1:8080'
- /**
- * 封装的请求方法
- * @param {Object} options - 请求配置
- * @param {String} options.url - 请求地址
- * @param {String} options.method - 请求方法,默认 GET
- * @param {Object} options.data - 请求参数
- * @param {Object} options.header - 额外的请求头
- * @returns {Promise}
- */
- const request = (options) => {
- return new Promise((resolve, reject) => {
- // 获取存储的 token
- const token = uni.getStorageSync('token') || ''
-
- uni.request({
- url: BASE_URL + options.url,
- method: options.method || 'GET',
- data: options.data || {},
- header: {
- 'Content-Type': 'application/json',
- 'clientid': CLIENT_ID,
- 'token': token,
- ...options.header
- },
- success: (res) => {
- const { code, msg, data, total, rows } = res.data
-
- // 根据状态码处理
- switch (code) {
- case 200:
- // 操作成功,返回数据
- if (total !== undefined && rows !== undefined) {
- // 分页查询返回体
- resolve({
- total,
- rows,
- code,
- msg
- })
- } else {
- // 一般返回体
- resolve({
- code,
- msg,
- data
- })
- }
- break
-
- case 401:
- // token 失效
- uni.showToast({
- title: 'token失效,请重新登录',
- icon: 'none',
- duration: 2000
- })
- // 清除 token
- uni.removeStorageSync('token')
- // 跳转到登录页(如果有的话)
- // uni.navigateTo({ url: '/pages/login/login' })
- reject({ code, msg: 'token失效' })
- break
-
- case 500:
- // 系统错误
- uni.showToast({
- title: '系统错误',
- icon: 'none',
- duration: 2000
- })
- reject({ code, msg: '系统错误' })
- break
-
- case 501:
- // 提示返回的 msg
- uni.showToast({
- title: msg || '请求失败',
- icon: 'none',
- duration: 2000
- })
- reject({ code, msg })
- break
-
- default:
- // 其他状态码
- uni.showToast({
- title: msg || '请求失败',
- icon: 'none',
- duration: 2000
- })
- reject({ code, msg })
- break
- }
- },
- fail: (err) => {
- uni.showToast({
- title: '网络请求失败',
- icon: 'none',
- duration: 2000
- })
- reject(err)
- }
- })
- })
- }
- export default request
|