uniapp使用第三方包配置网络请求

34 阅读1分钟

前言

由于小程序不支持 axios ,并且原生的 wx.request() API 功能比较简单,且不支持拦截器等全局定制的功能;可以在 uni-app 项目中使用 @escook/request-miniprogram 第三方包发起网络请求或者自己封装请求也可以:

详细信息可以查看官网:

官网: @escook/request-miniprogram - npm (npmjs.com)

安装

npm install @escook/request-miniprogram

导入

// 按需导入 $http 对象
import { $http } from '@escook/request-miniprogram'
 
// 将按需导入的 $http 挂载到 wx 顶级对象之上,方便全局调用
wx.$http = $http
 
// 在 uni-app 项目中,可以把 $http 挂载到 uni 顶级对象之上,方便全局调用
uni.$http = $http

使用

// 发起 GET 请求,data 是可选的参数对象
$http.get(url, data?)
 
// 发起 POST 请求,data 是可选的参数对象
$http.post(url, data?)
 
// 发起 PUT 请求,data 是可选的参数对象
$http.put(url, data?)
 
// 发起 DELETE 请求,data 是可选的参数对象
$http.delete(url, data?)

配置请求跟路径

$http.baseUrl = "xxxx.com"

相关配置

// 简单封装请求
uni.$http = $http
// 签名相关信息
const signatureKey = '签名KEY'
const generSign = (val) => CryptoJS.HmacSHA256(val, signatureKey).toString() ?? ''
$http.baseUrl = '
$http.beforeRequest = function(options) {
    // 添加请求头标识
    options.header = {
        'Content-type': 'application/json;charset=utf-8',
        timeStamp: timeStamp,
        versionCode: versionCode,
        userType: userType,
        userId: "",
    }
    if (!options.header.sign) {
        options.header['sign'] = generSign(JSON.stringify(options.data))
    }
    // 配置token
    if (store.state.token) {
        options.header.token = store.state.token
    }
    // 配置用户ID
    if (store.state.userId) {
        options.header.userId = store.state.userId
    }
    uni.showLoading({
        title: '数据加载中...',
    })
}
// 请求完成之后做一些事情
$http.afterRequest = function(response) {
    if (response.data.code === 100) {
        uni.$showMsg('需要重新登录')
    } else if (response.data.code !== 200) {
        uni.$showMsg(response.data.message)
    }
    uni.hideLoading()
}

欢迎访问我的博客:chu-yang.top:8018/?id=35