How uni-app configures network requests
Due to the limitation of the platform, axios is not supported in the applet project, and the original wx.request() API function is relatively simple, and does not support global customization functions such as interceptors. Therefore, it is recommended to use the @escook/request-miniprogram third-party package in the uni-app project to initiate network data requests.
1. Download
npm install @escook/request-miniprogram
2. In the main.js entry file, configure it in the following way
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()
}
3. Page call interface
async getGoodsDetail(goods_id) {
const {
data: res
} = await uni.$http.get('/api/public/v1/goods/detail', {
goods_id
})
if (res.meta.status !== 200) return uni.$showMsg()
},
Package pop-up prompt box
main.js
//封装弹框的方法
uni.$showMsg=function(title='数据请求失败!',duration=1500){
uni.showToast({
title,
duration,
icon:'none'
})
}
page call
uni.$showMsg()