封装小程序接口请求(request)

215 阅读1分钟

核心代码

config:{
        baseUrl:config.webUrl,
        header:{
                'Content-Type':'application/json;charset=UTF-8',
                'Content-Type':'application/x-www-form-urlencoded'
        },
        data: {},
        method: "GET",
        dataType: "json",
},
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.token) {
                // 验证用户是否登录
                if (!this.checkToken(options.checkToken)) return;
                // 验证用户操作权限(验证是否绑定手机号码)
                if (!this.checkAuth(options.checkAuth)) return;
                options.header.token = User.token;
        }
        return uni.request(options);
},
get(url,data,options={}){
        options.url = url;
        options.data = data;
        options.method = 'GET';
        return this.request(options);
},
post(url,data,options={}){
        options.url = url;
        options.data = data;
        options.method = 'POST';
        return this.request(options);
},

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'
		},
		data: {},
		method: "GET",
		dataType: "json",
	},
	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.token) {
			// 验证用户是否登录
			if (!this.checkToken(options.checkToken)) return;
			// 验证用户操作权限(验证是否绑定手机号码)
			if (!this.checkAuth(options.checkAuth)) return;
			options.header.token = User.token;
		}
		return uni.request(options);
	},
	get(url,data,options={}){
		options.url = url;
		options.data = data;
		options.method = 'GET';
		return this.request(options);
	},
	post(url,data,options={}){
		options.url = url;
		options.data = data;
		options.method = 'POST';
		return this.request(options);
	},
	// 上传图片
	upload(url,options = {}){
		options.url = this.config.baseUrl+url;
		options.header = options.header || this.config.header;
		options.fileType = options.fileType || "image";
		options.formData = options.formData || {};
		options.filePath = options.filePath;
		options.name = options.name;
		// TODO:token增加等操作
		if (options.token) {
			// 验证是否登录
			if (!this.checkToken(options.checkToken)) return;
			// 验证权限
			if (!this.checkAuth(options.checkAuth)) return; 
			options.header.token = User.token;
		}
		
		return uni.uploadFile(options);
	},
	// 错误处理
	errorCheck(err,res,errfun = false,resfun = false){
		if (err) {
			typeof errfun === 'function' && errfun();
			uni.showToast({ title: '加载失败',icon:"none" });
			return false;
		}
		if (res.data.errorCode) {
			typeof errfun === 'function' && resfun();
			uni.showToast({ title: res.data.msg,icon:"none" });
			return false;
		}
		return true;
	},
	// 验证用户是否登录
	checkToken(checkToken){
		if (checkToken && !User.token) {
			uni.showToast({ title: '请先登录', icon:"none" })
			uni.navigateTo({
				url: '/pages/login/login'
			});
			return false;
		}
		return true;
	},
	// 验证用户权限
	checkAuth(checkAuth){
		if (checkAuth && !User.userinfo.phone) {
			uni.showToast({ title: '请先绑定手机号码', icon:"none" })
			uni.navigateTo({
				url: '/pages/user-bind-phone/user-bind-phone'
			});
			return false;
		}
		return true;
	}
}

config.js

// 配置信息
export default {
	// api请求前缀
	webUrl:'https://ceshi2.dishait.cn/api/v1',
	// websocket地址
	websocketUrl:"wss://ceshi2.dishait.cn:23481",
	// 消息提示tabbar索引
	TabbarIndex:2
}

user.js

import $http from "./request.js"
export default {
	// 用户token 测试token:4cd36bf70649475ac0cd6fae78250954474a4350
	token:false,
	// 用户信息
	userinfo:false,
	// 用户相关统计
	counts:{},
	// 绑定第三方登录情况
	userbind:false,
	// 初始化
	__init(){
		// 获取用户信息
		this.userinfo = uni.getStorageSync("userinfo");
		this.token = uni.getStorageSync("token");
		this.counts = uni.getStorageSync("counts");
		this.userbind = uni.getStorageSync("userbind");
		this.OnUserCounts();
	},
	// 权限验证跳转
	navigate(options,type = "navigateTo"){
		// 是否登录验证
		if (!$http.checkToken(true)) return;
		// 验证是否绑定手机号
		if (!$http.checkAuth(true)) return;
		// 跳转
		switch (type){
			case "navigateTo":
			uni.navigateTo(options);
				break;
			case "redirectTo":
			uni.redirectTo(options);
				break;
			case "reLaunch":
			uni.reLaunch(options);
				break;
			case "switchTab":
			uni.switchTab(options);
				break;
		}
	},
	// 登录
	async login(options ={}){
		uni.showLoading({ title: '登录中...', mask: true });
		// 请求登录
		let [err,res] = await $http.post(options.url,options.data);
		// 登录失败
		if (!$http.errorCheck(err,res)){
			uni.hideLoading();
			return false;
		}
		// 登录成功 保存状态
		this.token = res.data.data.token;
		this.userinfo = this.__formatUserinfo(res.data.data);
		// 本地存储
		uni.setStorageSync("userinfo",this.userinfo);
		uni.setStorageSync("token", this.token);
		// 获取用户相关统计
		await this.getCounts();
		// 连接socket
		// 成功提示
		uni.hideLoading();
		uni.showToast({ title: '登录成功' });
		// 返回上一步
		if (!options.Noback) {
			uni.navigateBack({ delta: 1 });
		}
		return true;
	},
	// 退出登录
	async logout(showToast = true){
		// 退出登录
		await $http.post('/user/logout',{},{ 
			token:true,
			checkToken:true ,
		});
		// 清除缓存
		uni.removeStorageSync('userinfo');
		uni.removeStorageSync('token');
		uni.removeStorageSync('counts');
		// 清除状态
		this.token = false;
		this.userinfo = false;
		this.userbind = false;
		this.counts = {};
		// 关闭socket
		// 返回home页面
		uni.switchTab({ url:"/pages/home/home" })
		// 退出成功
		if (showToast) {
			return uni.showToast({ title: '退出登录成功' });
		}
	}
        
}