uniapp 封装request请求

2 篇文章 0 订阅
2 篇文章 0 订阅

uniapp request请求封装,vue axios也可用此模式封装

import store from "@/store/index.js"
var baseUrl = "http://192.168.0.1";
//baseUrl  为统一的配置的请求地址, 例如:http://192.168.0.1
//store 为vuex

// 封装请求
const request = (method, url, options) => {
	let methods = '';
	let headers = {};
	let token = store.state.token ? store.state.token : '';//存起来的token
	switch (method) {
		case 'get':
			methods = 'GET'
			headers = {
				'Content-Type': 'application/json;charset=UTF-8',
				'Authorization': token
			}
		break;
		case 'post':
			methods = 'POST'
			headers = {
				'Content-Type': 'application/json;charset=UTF-8',
				'Authorization': token
			}
		break;
		case 'postForm':
			methods = 'POST'
			headers = {
				'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
				'Authorization': token
			}
		break;
		default:
		break;
	}
	let hideLoading = false,
		loadingText = 'loading...';
	if (options) { //如果有options
		if (options.hideLoading) {
			hideLoading = options.hideLoading
			delete options.hideLoading
		}
		if (options.loadingText) {
			loadingText = options.loadingText
			delete options.loadingText
		}
	}
	
	//用Promise 返回后端返回的数据
	return new Promise((resolve, reject) => {
		if(!hideLoading){
			uni.showLoading({
				title: loadingText
			})
		}
		
		let urls = '';
		if (url.indexOf('http') == 0 || url.indexOf('https') == 0) {
			urls = `${url}`
		} else {
			urls = `${baseUrl}${url}`
		}
		uni.request({
			url: urls,
			method: methods,
			data: options,
			header: headers,
			success: res => {
				if (res.statusCode == 200) {
					if(res.data.recode == '200'){
						resolve(res.data);
					}else{
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						})
					}
				} else {
					uni.showToast({
						title: '请求错误(' + res.statusCode + ')',
						icon: 'none'
					})
					reject({
						'msg': '请求错误(' + res.statusCode + ')'
					})
				}
			},
			fail: e => {
				// checkError(e, reject);
				uni.showToast({
					title: '接口请求超时',
					icon: 'none'
				})
			},
			complete: () => {
				uni.hideLoading();
			}
		})
}


export default {
	get: (methods, url, options) => {
		return request('get', url, options)
	}
	// JOSN格式
	post: (url, options) => {
		return request('post', url, JSON.stringify(options))
	},

	// form-data格式
	postForm: (url, options) => {
		return request('postForm', url, options)
	},
}



然后main.js全局注册

Vue.$api = Vue.prototype.$api = api;

页面中使用

let urls = "user/checkUserPhone";//请求地址
let params = {id:1} //参数
this.$api.post(urls,params).then(res => {
	console.log("检查手机号是否存在", res)
})

以上方法如有问题欢迎指出,一起探讨,也可根据这个修改自己想要的方式

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值