| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140 |
- /**
- * 网络请求封装
- */
- import { t } from './i18n.js'
- // 固定的 clientid
- const CLIENT_ID = '2f847927afb2b3ebeefc870c13d623f2'
- // 基础 URL(根据实际情况修改)
- const BASE_URL = 'http://127.0.0.1:8080'
- /**
- * 获取当前语言环境
- * @returns {String} 语言代码(转换为下划线格式,如 zh_CN)
- */
- const getLanguage = () => {
- try {
- // 从本地存储获取语言设置,默认为 zh-CN
- const locale = uni.getStorageSync('locale') || 'zh-CN'
- // 将连字符转换为下划线格式(zh-CN -> zh_CN)
- return locale.replace('-', '_')
- } catch (e) {
- return 'zh_CN'
- }
- }
- /**
- * 封装的请求方法
- * @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') || ''
- // 获取当前语言环境
- const language = getLanguage()
-
- uni.request({
- url: BASE_URL + options.url,
- method: options.method || 'GET',
- data: options.data || {},
- header: {
- 'Content-Type': 'application/json',
- 'Content-Language': language,
- 'clientid': CLIENT_ID,
- 'Authorization': 'Bearer ' + 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:
- // 登录失效
- uni.showToast({
- title: t('common.error.unauthorized'),
- icon: 'none',
- duration: 2000
- })
- // 清除 token
- uni.removeStorageSync('token')
- // 跳转到登录页
- setTimeout(() => {
- uni.reLaunch({
- url: '/pages/login/login'
- })
- }, 2000)
- reject({ code, msg: t('common.error.unauthorized') })
- break
-
- case 500:
- // 系统错误
- uni.showToast({
- title: t('common.error.serverError'),
- icon: 'none',
- duration: 2000
- })
- reject({ code, msg: t('common.error.serverError') })
- break
-
- case 501:
- // 提示返回的 msg
- uni.showToast({
- title: msg || t('common.error.requestFailed'),
- icon: 'none',
- duration: 2000
- })
- reject({ code, msg })
- break
-
- default:
- // 其他状态码
- uni.showToast({
- title: msg || t('common.error.requestFailed'),
- icon: 'none',
- duration: 2000
- })
- reject({ code, msg })
- break
- }
- },
- fail: (err) => {
- uni.showToast({
- title: t('common.error.networkFailed'),
- icon: 'none',
- duration: 2000
- })
- reject(err)
- }
- })
- })
- }
- export default request
|