前端封装接口请求(uniapp)

以uniapp为例,封装接口请求。

使用的组件为graceUI

新建request.js文件
request.js

import graceJS from "@/Grace6/js/grace.js"

export const baseUrl = 'https://www.xxxxx'; //后端给你的接口地址前缀

export function createAuthorization(){
//每个请求携带token与加密等等,请根据实际情况写。这里就不赘述
}

//get请求
function _get(url, data = {}) {
	return new Promise((resolve, reject) => {
		graceJS.get(
			baseUrl + url, //接口地址:前缀+地址
			data,  //传递参数
			{
				Authorization: createAuthorization(), //自定义请求头
			},
			response => {
			//返回的数据(这里以code为200成功)
				if (response.code === 200) {
				//请求成功
					resolve(response)
				} else {
				//请求失败
					reject(response)
				}
			},
			error => {
			//请求失败
				reject(error)
			}
		)
	})
}

//post请求
function _post(url, data = {}) {
	return new Promise((resolve, reject) => {
		graceJS.post(
			baseUrl + url,  //接口地址:前缀+地址
			data,  //传递参数
			 {
				Authorization: createAuthorization(),//自定义请求头
			},
			response=> {
			//返回的数据(这里以code为200成功)
				if (response.code === 200) {
				//请求成功
					resolve(response)
				}else {
				//请求失败
					reject(response)
				}
			},
			error => {
			//请求失败
				reject(error )
			}
		)
	})
}

//导出
export function get(url, data) {
	return _get(url, data)
}
export function post(url, data = {}) {
	return _post(url, data)
}

这里统一将接口放在一起
例:tool.js

import { post ,get } from './request.js' //引入请求方法

const url = '/tool/'

//这里举了三个接口 /tool/compute、/tool/save、/tool/select 并命名

export const computeAPI = data => post(url + '/compute', data)

export const saveAPI = data => post(url + '/save', data)

export const selectCAPI = data => get(url + '/select', data)

使用:
例:order.js

import { computeAPI } from '@/tool.js' //引入接口



export default{
data(){
	return{
		id:1,
	}
},
methods:{
			//compute方法
			compute(){
				computeAPI ({
						id: this.id,
					}).then(res => {
						//返回数据
						console.log(res)
					}).catch(e => {
						//失败
						console.log(e)
					}).finally(() => {
						//结束
					})
			}
	}
}

这里只是最基本的一个封装,如果后端需要你传递其他东西,请自行增加修改

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值