foreword
-
When using uni-app to develop applets, I found that when axios added the request header, it did not add it in the actual network request.
-
Later, it was found that a third-party package @escookrequest-miniprogram sent the request instead of axios, and the request header was added normally.
-
Note that this package also wraps a layer of data in the outer layer, but it seems that it cannot be disposed of uniformly.
Code
1.下包@escookrequest-miniprogram
npm install @escook/request-miniprogram
2. Create a requesthttp.js folder under utils/ - the code is as follows
// 按需导入 $http 请求对象
import {
$http
} from '@escook/request-miniprogram'
// 将按需导入的 $http 挂载到 wx 顶级对象之上,方便全局调用
// wx这个东西是微信小程序里的顶级对象,也就是说所有页面都可以访问wx这个对象
// 所以我所有地方就可以用 wx.$http访问到请求对象了
// 设置基地址
$http.baseUrl = 'http://127.0.0.1:8800'
// 在 uni-app 项目中,可以把 $http 挂载到 uni 顶级对象之上,方便全局调用
// 小程序里wx是顶级对象,但是在uniapp中,uni才是顶级对象
uni.$http = $http
// 请求开始之前做一些事情
// 因为咱们是uniapp项目,顶级对象不叫wx,叫uni,记得把wx这个改成uni
$http.beforeRequest = function(options) {
console.log('请求参数', options);
options.header = {
'token': uni.getStorageSync('token'),
'tenant-id': uni.getStorageSync('tenant-id')
}
uni.showLoading({
title: '数据加载中...',
})
// console.log('请求参数添加之后', options);
}
// 请求完成之后做一些事情
$http.afterRequest = function(res) {
console.log('请求之后', res);
uni.hideLoading()
}
3. Introduce in main.js
// 请求导入即可
import "./utils/requesthttp.js"
4. Page send request
4.1 get request
// 默认多包了一层data,解构出来
const {
data: res
} = await uni.$http.get('/equipment/getSystemType')
console.log('数据', res);
4.2 get request splicing path parameters
// 默认多包了一层data,解构出来
// 传递路径id数字类型需要模板字符串
方法(id){
const {
data: res
} = await uni.$http.get(`/wechat-inspection/getFloor/${id}`)
}
Summarize:
After this process, I believe you also have a preliminary deep impression on uni-app using @escookrequest-miniprogram request sending, but the situation we encounter in actual development is definitely different, so we need to understand its principle , ever-changing remains the same. Come on, hit the workers!
Please point out any deficiencies, thank you -- Fengguowuhen