uni-app开发小程序封装API接口请求

在这里插入图片描述

一、建立一个https.js文件(接口地址根据自己的地址填写)

// 区分开发环境和生产环境  接口地址
let baseUrl;

if (process.env.NODE_ENV === 'development') {
    baseUrl = 'xxxxxxxxxxx'    // 开发环境
} else {
	baseUrl = 'xxxxxxxxxxx'    // 生产环境
}

export function https(config) {
	//显示loading
	wx.showLoading({
		title: '加载中...'
	});	
	//设置请求头
	config.header = {
		'content-type': 'application/json',
	};
	//检查缓存中有没有token
	var token = wx.getStorageSync('token');
	if (token != '') {
		header.Authorization = token
	}	
	config.url = baseUrl + config.url;   // 请求地址
	let promise = new Promise(function(resolve, reject) {
		uni.request(config).then(res => {
			wx.hideLoading()      //隐藏loading
			if (res[0]) {
				uni.showToast({
					title: "数据获取失败",
					icon: "none",
					duration: 1500
				})
				resolve(false);
			} else {
				let data = res[1].data; 
				if (data.code == 1) {
					resolve(data);
				} else {
					resolve(data);
				}
			}
		}).catch(error => {
			wx.hideLoading()      //隐藏loading
			reject(error);
		})
	})
	return promise
}

二、再建立一个api.js文件,引入刚刚封装好的https.js文件。api是作为一个接口集

import {https}  from '@/components/api/https.js';    // 引入刚刚封装好的https
	
class api{
	async getList(data) {
		const res = await https({
			method: "get", // 请求方式
			url: '/getJoke', // 请求url
			data: data,// 参数
		})
		return res
	}
	// 下面可以接着写API接口集
	// 接口二
	// 接口三
	// ......
}

export default new api()

三、main.js全局引用刚刚封装好的API接口集,绑定到原型

import api from './components/api/api.js'
Vue.prototype.$dy_api = api

四、页面调用(没有参数可不写)

getData(){		
	this.$dy_api.getList({page:"1",count:"2",type:"video"}).then((res)=>{
	console.log(res)
  })	
}

请求结果图
ycl.png

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值