uni-app的uni-request封装方法

最近开始写uni-app,由于请求头太多,所以需要把uni-request封装一下。接下来记录一下它的封装方法。

1 写一个request.js,写在最外层

import uniRequest1 from 'uni-request';
let baseURL='http://192.168.0.254:8011';
function myRequest(options){
	let headers={}
	var Token =uni.getStorageSync('Token');
	var UserId =uni.getStorageSync('UserId');
	var sign=date_hao+UserId;
	var hash=hex_md5(sign);
	
	headers['HBWS-Client-DateTime'] = date_d;
	headers['HBWS-Client-Timestamp'] = date_hao;
	headers['HBWS-Client-Token'] = Token;
	headers['HBWS-Client-Sign'] = hash;
	headers['HBWS-Client-UserId'] = UserId;
	headers["Content-Type"] = "application/json";
	return new Promise((res,rej)=>{
		uni.request({
			url:baseURL + options.url,
			method:options.method || 'GET',
			data:options.data,
			header:headers,
			success(data) {
				res(data)
			},
			fail() {
				rej()
			}
		})
	})
	
}
export default myRequest;

 

2 挂载在main.js

import myRequest from '@/request.js'
Vue.prototype.$myRequest = myRequest

 

3 在需要的地方引用

                         _this.$myRequest({
					method:'GET',
					url:'/api/DiscloseUserInfo/GetNoticeAllList',
					data:{
						"uiserid":uni.getStorageSync('UserId'),
						"pageSize":_this.pageSize,
						"pageNumber":_this.cur_page
					}
				})
			   .then(res2=>{
					console.log(res2);
					if(res2.data.ResultType==0){
						uni.showToast({
						    title: '加载中......',
							icon:'loading',
						    duration: 500
						});
					  _this.rows=res2.data.Data.DataList;
					  _this.totalVal=res2.data.Data.TotalCount;
					}
			   })
			   .catch(error=>{
					console.log(error);
				});

由于需要引用从别的页面的存储,所以这种封装方法是比较万能的。

发布了110 篇原创文章 · 获赞 9 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Lemontree_fu/article/details/103304216