当前位置:网站首页>Uni app third party package configuration network request

Uni app third party package configuration network request

2022-07-06 07:06:00 Front end childe Jia

Due to the limitation of the platform , Not supported in applet projects axios, And the original  wx.request() API The function is relatively simple , Global customization functions such as interceptors are not supported . therefore , It is suggested that uni-app Project use  @escook/request-miniprogram  Third party packet initiates network data request .

Please refer to  @escook/request-miniprogram  Official installation documentation 、 To configure 、 Use

Official documents :https://www.npmjs.com/package/@escook/request-miniprogram

1. initialization npm package

npm init -y		 Initialize at project root package.json file 

npm i @escook/request-miniprogram -S  Download network request package 

2. open main.js Entrance file

import { $http } from '@escook/request-miniprogram'
// Introduce... From the network request packet $http Request object 
uni.$http = $http
// Because it is also used in other pages or components , So will $http The object is attached to the global object , stay uni-app in ,uni Global object 
$http.baseUrl = 'https://www.baidu.com'
// Configure network request base address , because uni.$http by $http References to , So you can modify it directly $http Properties under the object 
$http.beforeRequest = function() {
    // Configure the interception function before initiating the network request 
    uni.showLoading({
        title: ' Loading ...'
    })
}
$http.afterRequest = function() {
    // Configure the interception function after the network request 
    uni.hideLoading()
}

//  Encapsulation request failure prompt 
uni.$showMsg = function(title=' Data load failed ',duration=1500){
	uni.showToast({
		title,
		duration,
		icon:'none'
	})
}

3. Initiate network request

async getSwiperList() {
   const { data: res } = await uni.$http.get('/api/public/v1/home/swiperdata')
   if (res.meta.status !== 200) return uni.$showMsg()
   this.swiperList = res.message
}

原网站

版权声明
本文为[Front end childe Jia]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131946076667.html