学习笔记(5)uni-app封装请求api并导出

简介

目前项目的接口配置流程:添加接口,封装请求,批量导出,挂载到全局对象上,在页面上使用。
其中,封装请求,批量导出,挂载已经设置完毕,无须修改。
如果要在项目中,继续添加接口,请注意导出的接口名字要具有唯一性

添加接口

// 登录,所有的请求
import request from './http.js';
const api = request

// 获取验证码
export const loginPic = () => {
   return api.request('/app/captcha/loginPic/v1.0/56685', 'GET')
}

// 登录
export const login = (data) => {
   return api.request('/app/login/login/v1.0/56685', 'POST', data)
}

//例如:要在登录页添加一个接口,loginNewApi必须保证在整个项目的接口文件中,只有一个。
export const loginNewApi = (data) => {
   return api.request('/app/login/new/v1.0/56685', 'POST', data)
}

封装请求

路径:@/pages/api/http.js。
第二步和pc端的一样。

import store from '../store/index.js'

// const baseUrl = '/api' //dev环境
// const baseUrl = 'http://app.dev.com:8222' //dev环境
// const baseUrl = 'http://test.com.cn:8222'  //test环境
const baseUrl = 'https://app.pro.com.cn'  //pro环境
const ignore = [
	'/app/login/isLogin/v1.0/56685',
	'/app/captcha/loginPic/v1.0/56685',
	'/app/login/initSession/v1.0/56685',
	'/app/login/viewSessionId/v1.0/56685'
]
let ajaxTimes = 0;
const request = (url, method, data) => {
 	//可在此处添加请求拦截器,例如对请求参数加密
	const session = uni.getStorageSync('SESSION');
	return new Promise((resolve, reject) => {
		if (ignore.indexOf(url) == -1) {
			uni.showLoading({
				title: '加载中',
				mask: true
			});
		}
		ajaxTimes++;
		uni.request({
			method: method,
			url: baseUrl + url,
			data: data,
			// withCredentials: true,
			xhrFields: {
				// withCredentials: true
			},
			header: {
				'content-type': 'application/x-www-form-urlencoded',
				'X-Auth-Token': session
			},
			dataType: 'json',
		}).then((response) => {
			let [error, res] = response;
			ajaxTimes--;
			if (res.statusCode == 200 && res.data.status == 200) {
				if (ajaxTimes === 0) {
					setTimeout(function() {
						uni.hideLoading();
					}, 300);
				}
              	//可以在这添加响应拦截器,对响应数据对个性化的处理
				resolve(res.data);
			}
			else if (res.statusCode == 200 && res.data.status == 403) {
				uni.hideLoading();
				uni.showToast({
					title: '登录失效!',
					icon: 'none'
				})
				reject(res.data);
				uni.reLaunch({
					url: '/pages/views/login/login'
				})
			}
			else {
				if (ajaxTimes === 0) {
					setTimeout(function() {
						uni.hideLoading();
					}, 300);
				}
				uni.showToast({
					title: res.data.msg,
					icon: 'none'
				})
				reject(res.data);
			}
		}).catch(error => {
			uni.hideLoading();
			uni.showToast({
				title: '网络错误!',
				icon: 'none'
			})
			let [err, res] = error;
			reject(err)
		})
	});
};

const htmlRequest = (url, method, data) => {
	const session = uni.getStorageSync('SESSION');
	return new Promise((resolve, reject) => {
		uni.request({
			method: method,
			url: baseUrl + url,
			data: data,
			// withCredentials: true,
			xhrFields: {
				// withCredentials: true
			},
			header: {
				'content-type': 'application/x-www-form-urlencoded',
				'X-Auth-Token': session
			},
			dataType: 'html',
		}).then((response) => {
			let [error, res] = response;
			if (res.statusCode == 200) {
				resolve(res.data);
			} else {
				reject(res.data);
			}
		}).catch(error => {
			let [err, res] = error;
			reject(err)
		})
	});
}

export default {
	baseUrl,
	request,
	htmlRequest
}

全部导出

路径:@/pages/api/index.js

// 该文件用于合并所有接口文件并批量导出所有的接口请求
const requireApi = require.context(
	// api 的相对路径
	'.',
	// 是否查询子目录
	false,
	// 查询文件的后缀
	/.js$/
)
let module = {} // 用于存放接口并一起导出
requireApi.keys().forEach((key,index) => {
	if(key == './http.js') return // 过滤http.js文件
	Object.assign(module,requireApi(key))
})
//导出所有接口请求
export default module

挂载到全局对象上

路径:@/main.js

// 1,模块化请求,全局引入index.js
import Api from '@/pages/api/index.js'
Vue.prototype.$Api = Api//  2、挂载全局
Vue.prototype.$store = store

页面上使用

this.$Api.login(param).then(res => {
		console.log(res)
})
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

酒鼎

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值