前段API封装

前段API封装

创建一个api.js文件,代码内容如下

class ApiService {
	constructor() {
		this.api_root = '域名';
		this.Auth = false //当前接口是否需要登录
	}

	_request(method, url, data = {}, success, fail, complete) {
		let is_login = this.Auth
		console.log('url', url)
		// 检查是否需要验证登录状态
		if (is_login) {
			const token = uni.getStorageSync('token');
			if (!token) {
				console.log('表哥我出来了哦')
				uni.showModal({
					title: '登录提示',
					content: '您尚未登录,请先登录',
					showCancel: false, // 不显示取消按钮
					success: () => {
						// 跳转到登录页面
						uni.reLaunch({
							url: '/pages/common/login/login'
						});
					}
				});
				return;
			}
			// 如果有token,将token添加到请求头中
			this.header = {
				'content-type': method.toUpperCase() === 'GET' ? 'application/json' :
					'application/x-www-form-urlencoded',
				'token': `${token}`
			};
		} else {
			this.header = {
				'content-type': method.toUpperCase() === 'GET' ? 'application/json' :
					'application/x-www-form-urlencoded'
			};
		}

		const requestData = Object.assign({

		}, data);

		uni.request({
			url: this.api_root + url,
			method,
			header: this.header,
			data: method.toUpperCase() === 'GET' ? {
				...requestData
			} : this._encodeFormData(requestData),

			success(res) {
				if (res.statusCode !== 200 || typeof res.data !== 'object') {
					fail && fail(res);
					return;
				}
				switch (res.data.code) {
					case -1:
					case 0:
						success && success(res.data);
						break;
					default:
						success && success(res.data);
						break;
				}
			},
			fail(res) {
				fail && fail(res);
			},
			complete(res) {
				uni.hideNavigationBarLoading();
				complete && complete(res);
			}
		});
	}

	_encodeFormData(data) {
		const formData = [];
		for (const key in data) {
			formData.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
		}
		return formData.join('&');
	}

	get(url, data, success, fail, complete) {
		this._request('GET', url, data, success, fail, complete);
	}

	postForm(url, data, success, fail, complete) {
		this._request('POST', url, data, success, fail, complete);
	}
}

const apiService = new ApiService();
export default apiService;

调用方法如下

引入api.js

import apiService from './api.js';

GET请求

apiService.Auth = false //当前接口不需要登录
apiService.get('some-get-api', { param1: 'value1' }, (data) => {
  console.log('请求成功', data);
}, (error) => {
  console.log('请求失败', error);
}, () => {
  console.log('请求完成');
});

POST请求

apiService.Auth = true //当前接口需要登录
apiService.postForm('some-post-api', { param1: 'value1' }, (data) => {
  console.log('请求成功', data);
}, (error) => {
  console.log('请求失败', error);
}, () => {
  console.log('请求完成');
});
© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享
xiaoshan的头像-闪狐博客
评论 抢沙发

请登录后发表评论

    暂无评论内容