前言:
由于平台的限制,小程序项目中不支持 axios,而且原生的 wx.request()
API 功能较为简单,不支持拦截器等全局定制的功能。因此,建议在 uni-app 项目中使用 @escook/request-miniprogram
第三方包发起网络数据请求。
安装:
npm install @escook/request-miniprogram
在项目的 main.js
入口文件中,通过如下的方式进行配置:
import { $http } from '@escook/request-miniprogram'
uni.$http = $http
// 配置请求根路径
$http.baseUrl = 'https://www.uinav.com'
// 请求开始之前做一些事情
$http.beforeRequest = function (options) {
uni.showLoading({
title: '数据加载中...',
})
}
// 请求完成之后做一些事情
$http.afterRequest = function () {
uni.hideLoading()
}
支持的请求方法
// 发起 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 = 'https://www.example.com'
请求拦截器
// 请求开始之前做一些事情
$http.beforeRequest = function (options) {
// do somethimg...
}
自定义 header 请求头:
// 请求开始之前做一些事情
$http.beforeRequest = function (options) {
if (options.url.indexOf('/home/catitems') !== -1) {
options.header = {
'X-Test': 'AAA',
}
}
}
响应拦截器
// 请求完成之后做一些事情
$http.afterRequest = function () {
// do something...
}
项目实战使用: