ajax请求封装

Posted by     小兵兵 on Wednesday, April 29, 2020

目录

uni-app原始请求

uni.request({
	url: '',
	method: 'GET',
	data: {},
	success: res => {
		//成功时,进行数据的处理
        console.log(res.data)
	},
	fail: () => {},
	complete: () => {}
});

对原始uni-app请求进行二次封装

创建common文件夹,新建util.js

直接将函数success里的res.data能不能直接return,显然是不行的,那样返回出去会导致请求返回结果为undefined

异步处理需要用Promise包装起来整个返回出去

function ajax(url,data={},method='GET') {
	return new Promise((resolve,reject)=>{
		uni.request({
			url: url,
			method,
			data,
			success: res => {
				resolve(res.data)
			},
			fail: (error) => {
				reject(error)
			},
			complete: () => {}
		});
	})
}
export {
	ajax
}

创建api.js接口文件

import {
	ajax
} from '@/common/util.js'


let baseUrl = 'http://192.168.1.101:8080'

//预约管理
//获取默认预约指标
export const getAppointmentTargetDefaultConf =(param)=> ajax(`${baseUrl}/hnddcb/appointmentTarget/getAppointmentTargetDefaultConf.do`,param)
//修改默认预约指标
export const updateAppointmentTargetDefaultConf =(param)=> ajax(`${baseUrl}/hnddcb/appointmentTarget/updateAppointmentTargetDefaultConf.do`,param,'POST')
//根据日期获取预约指标数据
export const getAppointmentTargetByDateTime =(param)=> ajax(`${baseUrl}/hnddcb/appointmentTarget/getAppointmentTargetByDateTime.do`,param)

调用api接口

对接口的调用结果处理有2种语法|async、await|then|,推荐使用async、await,语法更简洁

<template>
	<view class="container">
		<view class="intro">本项目已包含uni ui组件,无需import和注册,可直接使用。在代码区键入字母u,即可通过代码助手列出所有可用组件。光标置于组件名称处按F1,即可查看组件文档。</view>
		<text class="intro">详见:</text>
		<uni-link :href="href" :text="href"></uni-link>
	</view>
</template>

<script>
	import {
		getAppointmentTargetDefaultConf,
		updateAppointmentTargetDefaultConf,
		getAppointmentTargetByDateTime
	} from '@/common/api.js'

	export default {
		data() {
			return {
				href: 'https://uniapp.dcloud.io/component/README?id=uniui'
			}
		},
		methods: {
			//获取预约指标默认值
			async getData() {
				let para = {
					id: 1,
					name: '沈利兵',
					age: 18
				}
				let res = await getAppointmentTargetDefaultConf(para)
				console.log(res)
			},

			//修改预约指标默认值
			async updateAppointmentTargetDefaultConf() {
				let para = {
					appointTarget: 4,
					appointTimeSlot: '09:00-09:59,10:00-10:59,11:00-11:59,12:00-13:59',
					appointTimeSlotTarget: '1,1,1,1'
				}
				let res = await updateAppointmentTargetDefaultConf(para)
				console.log(res)
			},
			//根据日期获取预约指标数据
			getAppointmentTargetByDateTime() {
				let para = {
					date: '2020-05-20'
				}
				getAppointmentTargetByDateTime(para).then((res) => {
					console.log(res)
				}).catch((res) => {
					console.log(res)
				})

			}


		},
		mounted() {
			this.getData()
			this.updateAppointmentTargetDefaultConf()
			this.getAppointmentTargetByDateTime()
		}
	}
</script>

<style>
	.container {
		padding: 20px;
		font-size: 14px;
		line-height: 24px;
	}
</style>

目录结构

tips

导入

// 绝对路径,@指向项目根目录,在cli项目中@指向src目录
import add from '@/common/add.js'
// 相对路径
import add from '../../common/add.js'

参考

JavaScript Visualized: Promises & Async/Await

request 请求拦截