UniApp Api接口封装

全局注册,通过this调用
适用于vue 跟 uniapp

在uniapp 下
跟pages同级下
创建一个api文件夹下
在创建一个http.js

在这里插入图片描述
1.http.js

//服务器地址
const service = "域名/ip地址";

module.exports = (params) => {
	let url = params.url;
	let method = params.method;
	let header = params.header || {};
	let data = params.data || {};
	//	请求方式 GET POST
	if (method) {
		method = method.toUpperCase(); //	小写转大写
		if (method == "POST") {
			header = {
				"content-type": "application/x-www-form-urlencoded"
			}
		}
	}
	//	发起请求 加载动画
	if (!params.hideLoading) {
		uni.showLoading({
			title: "加载中"
		})
	}
	//	发起网络请求
	uni.request({
		url: service + url,
		method: method || "GET",
		header: header,
		data: data,
		dataType: "json",
		sslVerify: false, //	是否验证ssl证书
		success: res => {
			console.log(res)
			if (res.data.code && res.data.code != 200) {
				//	api错误
				uni.showToast({
					title:res.data.info,
					icon:'none'
				})
				return;
			}
			typeof params.success == "function" && params.success(res.data);
		},
		fail: err => {
			uni.showToast({
				title:res.data.info,
				icon:'none'
			})
			typeof params.fail == "function" && params.fail(err.data);
		},
		complete: (e) => {
			console.log("请求完成");
			uni.hideLoading()
			typeof params.complete == "function" && params.complete(e.data);
			return;
		}
	})
}

2:在main.js注册全局

main.js文件

import Vue from 'vue'
import App from './App'
import http from './api/http.js'

const msg = (title, duration=1500, mask=false, icon='none')=>{
	//统一提示方便全局修改
	if(Boolean(title) === false){
		return;
	}
	uni.showToast({
		title,
		duration,
		mask,
		icon
	});
}

Vue.config.productionTip = false
Vue.prototype.http = http
Vue.prototype.$api = {msg};

App.mpType = 'app'

const app = new Vue({
    ...App
})
app.$mount()

3:调用接口

		onLoad() {
          this.http({
			  url:'域名/ip地址',
			  method:'GET',
			  	success: res => {	
			  				console.log(res)
			  			},
			  			fail: err => {
			  				console.log(res)
			  			}
		  })
		},
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值