uniapp请求接口的封装,前端请求方法

在用uni-app开发项目的时候,尽管可以使用官方的uni.request()请求方法跟后台数据交互,但是仍然需要对前端接口跟据业务进行代码封装,不封装代码使用,使用起来会容易乱成一团,维护和管理都麻烦,日后不仅会使代码难以看懂,而且不好维护和增加新功能。封装好之后不管迭代多少版本,接口可以统一调用和维护,会舒服很多。

前端请求接口,简单来说就是从服务器上获取,修改,删除数据,并将数据展示在页面上。下面是最基本的请求方法api。

uni.request({
    url: 'https://www.example.com/request', //仅为示例,并非真实接口地址。
    data: {
        text: 'uni.request'
    },
    header: {
        'custom-header': 'hello' //自定义请求头信息
    },
    success: (res) => {
        console.log(res.data);
        this.text = 'request success';
    }
});

这里的代码并没有问题,也可以正常的使用,也实现了功能,但是当接口多起来的时候,添加的代码也会越来越多,到那时候代码看起来会很混乱,维护起来会非常麻烦。

那么如何封装了?

1、可以从通用的常量进行封装,比如把url,header,放到单独的配置文件中。

//config.js

//是否是测试版本 true:测试版 | false:正式版
const isTest = false;
let config=null;

if(isTest){
   
    config={
         // #ifdef H5
	    apiUrl:'/api',//h5使用代理
	    
	    // #endif
        // #ifndef H5
        apiUrl:'https://devlopment.requesturl.cn',
	    fileUrl:'', // 文件基础路径
         // #endif
        headers:{
				'content-type': 'application/x-www-form-urlencoded'
			}
    }


}else{
    config={
        apiUrl:'https://product.requesturl.cn',
	    fileUrl:'', // 文件基础路径
        headers:{
				'content-type': 'application/x-www-form-urlencoded'
			}
    }

}
//导出对象
export default config;


//请求文件里引入
 import  config from '文件位置。。。'




       请求接口文件里的封装

// 引入配置
import config from './config.js';

uni.request({
    url: config.apiUrl。
    data: {
        text: 'uni.request'
    },
    header: config.header,
    success: (res) => {
        console.log(res.data);
        this.text = 'request success';
    }
});

到时要修改常量的时候,到配置文件里修改就可以了 ,代码维护起来就容易多了。

到现在仍然是半封装状态,还没有完全完成封装,仍然有大量的工作要做。比如要检查请求入参,token那么些,也要统一处理,还有请求服务器之后,返回的数据也需要进行处理和错误提示等等。用Promise进行封装。

//引入入参和出参检查方法
import {requestInterceptors,responseInterceptors} from './interceptors.js';
//定义一个新的请求接口

function request(params){

    //检查入参
	if(!requestInterceptors(params)){
		return;
	}
    let postData=params.data || {}
    //发起请求
    return new Promise(function (resolve, reject) {
         uni.request({
			 url:config.apiUrl + params.url,
			
			//请求头
			header: config.header
			method:params.requestType || 'POST',//post get
			data:postData,
			complete: (res) => {
				
				
				responseInterceptors(res,params,reslove,reject);
			}
		});

    })
   


}

//导出接口
export default request;

到此已经完成了封装,有些修改,也可以在各自的配置文件里进行修改。结构清晰,代码优雅。

如何在页面调用,先要在main.js文件里挂载请求方法,方便全局调用。

//main.js
import App from './App';
import request from '文件位置...'
import Vue from 'vue';



Vue.prototype.$api=request;

const app = new Vue({
	App
});

最在页面调用就行了

 

//index.vue

export default {
		data() {
			return {
				list:[]
			}
		},
		onLoad() {
			this.getData()
		},
		methods: {
			getData(){
				this.$api({
					url:'apidata',
					success:(res)=>{
						console.log("res===>",res)
						//执行业务代码
						//this.list=res.data
					},
					
				
			}
			
		}
	}

前端,uniapp接口封装完成 。

请求接口demo下载:https://business-1257642555.cos.ap-guangzhou.myqcloud.com/softpay/requestDemoPro.zip

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值