Skip to content

uniapp

条件编译

提示: Uni-app 平台标识符常用 MP-WEIXIN (微信)、H5MP-ALIPAYAPP-PLUS (原生App)。

在 "JS/TS" 中

js
// #ifdef H5
console.log('仅在 H5 端运行')
// #endif

// #ifndef MP-WEIXIN
console.log('不在 微信小程序端 运行')
// #endif

在 "Vue Template" 中

html
<view>仅在 H5 展示</view>
<view>仅在 微信小程序 展示</view>

在 "CSS" 中

css
/* #ifdef H5 */
.title {
  color: red;
}
/* #endif */

/* #ifdef MP-WEIXIN */
.title {
  color: blue;
}
/* #endif */

在 "pages.json" 中

注:用于针对不同平台配置不同的页面路径或导航栏样式。

json
// #ifdef MP-WEIXIN
{
  "path": "pages/weixin/index",
  "style": { "navigationBarTitleText": "微信特有页面" }
}
// #endif

请求拦截

js
uni.addInterceptor('request', {
  // 请求前拦截
  invoke(args) {
    // 1. 注入 Token
    args.header = {
      ...args.header,
      Authorization: 'Bearer ' + (uni.getStorageSync('token') || ''),
    }
    // 2. 修改 URL(如拼接基地址)
    args.url = 'https://api.example.com' + args.url

    console.log('发送请求:', args)
  },
  // 响应后拦截
  success(res) {
    if (res.statusCode === 401) {
      // 处理登录失效
      uni.navigateTo({ url: '/pages/login/login' })
    }
    return res
  },
  fail(err) {
    console.error('请求失败:', err)
  },
})

例如:

js
import { isProd } from './env.js'

const baseUrl = 'https://dummyjson.com'

// 拦截器
const requestInterceptor = {
  // 拦截前触发
  invoke(options) {
    // baseUrl 拼接
    if (!options.url.startsWith('http')) {
      options.url = baseUrl + options.url
    }
    // options.timeout = 3000
    options.header = {
      ...options.header,
    }
    const token = uni.getStorageSync('token')
    if (token) {
      // options.header.Authorization = token
    }
  },
}
uni.addInterceptor('request', requestInterceptor)
uni.addInterceptor('uploadFile', requestInterceptor)

// 请求方法封装
export const request = (option) => {
  return new Promise((resolve, reject) => {
    uni.request({
      ...option,
      // 响应成功
      success(res) {
        console.log(res)
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data)
        } else if (res.statusCode === 401) {
          // 清理登录信息
          // TODO

          // 跳转登录页
          uni.navigateTo({
            url: '/pages/login/login',
          })
          reject(new Error('无权限'))
        } else {
          const errorMsg = res.data.message || '请求错误'
          uni.showToast({
            icon: 'none',
            title: errorMsg,
          })
          reject(errorMsg)
        }
      },
      // 响应失败(网络错误)
      fail(err) {
        reject(err)
      },
    })
  })
}

export const get = (url, params = {}) => {
  return request({
    url,
    method: 'GET',
    data: params,
  })
}

export const post = (url, data = {}) => {
  return request({
    url,
    method: 'POST',
    data,
  })
}

export const put = (url, data = {}) => {
  return request({
    url,
    method: 'PUT',
    data,
  })
}

export const del = (url, data = {}) => {
  return request({
    url,
    method: 'DELETE',
    data,
  })
}

基于 MIT 许可发布