1 Introduction
Due to the limitation of the platform, axios is not supported in the applet project , and the native wx.request()
API functions are relatively simple, and global customization functions such as interceptors are not supported . Therefore, it is recommended to use third-party packages in the uni-app project @escook/request-miniprogram
to initiate network data requests.
Official documentation: @escook/request-miniprogram - npm
2. Configuration steps
1. Use npm installation in the project root directory
npm install @escook/request-miniprogram
@escook
If there is a folder under node_modules as shown in the figure , the installation is successful
2. Configure http in main.js
// 导入网络请求的包
import { $http } from '@escook/request-miniprogram'
uni.$http = $http
// 请求的根路径
$http.baseUrl = 'https://api-hmugo-web.itheima.net'
// 请求拦截器
$http.beforeRequest = function(options) {
uni.showLoading({
title: '数据加载中...'
})
}
// 响应拦截器
$http.afterRequest = function() {
uni.hideLoading()
}
3. Detailed explanation
According to the interface requirements, the commonly used request types are get request and post request
res is the data returned by the interface, which may include 1. Request result status (success) 2. Data (data) 3. Prompt (message)
get request uni.$http.get; post request uni.$http.post
4. Examples
Add the method of getting the carousel map in home.vue
export default {
data() {
return {
// 1. 轮播图的数据列表,默认为空数组
swiperList: [],
}
},
onLoad() {
// 2. 在小程序页面刚加载的时候,调用获取轮播图数据的方法
this.getSwiperList()
},
methods: {
// 3. 获取轮播图数据的方法
async getSwiperList() {
// 3.1 发起请求
const { data: res } = await uni.$http.get('/api/public/v1/home/swiperdata')
// 3.2 请求失败
if (res.meta.status !== 200) {
return uni.showToast({
title: '数据请求失败!',
duration: 1500,
icon: 'none',
})
}
// 3.3 请求成功,为 data 中的数据赋值
this.swiperList = res.message
},
},
}
get request return example
{
"message": [
{
"image_src": "https://api-ugo-web.itheima.net/pyg/banner1.png",
"open_type": "navigate",
"goods_id": 129,
"navigator_url": "/pages/goods_detail/index?goods_id=129"
}
],
"meta": {
"msg": "获取成功",
"status": 200
}
}