uniApp 请求接口封装,自认为还可以

commons目录下加 request.js

 

// 引入配置文件
import config from "./config.js";
import User from "./user.js";
export default{
	config:{
		baseUrl:config.webUrl,
		header:{
			'Content-Type':'application/json;charset=UTF-8',
			'Content-Type':'application/x-www-form-urlencoded',
			'Authorization':uni.getStorageSync('token'),
		},
		data: {},
		method: "GET",
		dataType: "json",
		withCredentials: true
	},
	request(options = {}){
		// options.header || 
		options.header = this.config.header;
		options.method = options.method || this.config.method;
		options.dataType = options.dataType || this.config.dataType;
		options.url = this.config.baseUrl+options.url;
		// TODO:token增加等操作
		if (options.Authorization) {
			// 验证用户是否登录
			if (!this.checkToken(options.checkToken)) return;
			// 验证用户操作权限(验证是否绑定手机号码)
			if (!this.checkAuth(options.checkAuth)) return;
			options.header.Authorization = User.token;
		}
		return uni.request(options);
	},
	// get 方法
	get(url,data,options={}){
		options.url = url;
		options.data = data;
		options.method = 'GET';
		return this.request(options);
	},
	// post 方法
	post(url,data,options={}){
		this.config.header.Authorization = uni.getStorageSync('token');
		options.url = url;
		options.data = data;
		options.method = 'POST';
		return this.request(options);
	},
	// 错误处理
	errorCheck(err,res,errfun = false,resfun = false){
		console.log(err)
		if (err) {
			typeof errfun === 'function' && errfun();
			uni.showToast({ title: 'fail to load',icon:"none" });
			return false;
		}
		
		if (res.data.code) {
			typeof errfun === 'function' && resfun();
			uni.showToast({ title: res.data.errorMessage,icon:"none" });
			return false;
		}
		return true;
	},
}

 

main.js

import request from "./commons/request.js";
Vue.prototype.$http = request;

引入示例

async register(data) {
    let [err, res] = await this.$http.post('/userCt/login', {
				   //请求账号密码登录接口
				password: this.password,
				userName: this.mobile
			});
// 这里是错误的回调,如果请求的接口错误,或者需要自定义返回的日志,可以在这里处理
			if (!this.$http.errorCheck(err, res)) return;
			if (res.data.code == 0) {
				//这里这里是成功的回调
			}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章