uniapp 接口封装

luch-request与uni.request比较

luch-request

https://github.com/lei-mu/luch-request

luch-request 是一个基于Promise 开发的uni-app跨平台、项目级别的请求库,它有更小的体积,易用的api,方便简单的自定义能力。

支持全局挂载
  1. 支持多个全局配置实例
  2. 支持自定义验证器
  3. 支持文件上传/下载
  4. 支持task 操作
  5. 支持自定义参数
  6. 支持多拦截器
  7. 对参数的处理比uni.request 更强
方法一: luch-request 

安装依赖 // uview使用的封装接口

npm install luch-request -S

@/config/request.js

import Request from 'luch-request'
import { baseUrl } from './index.js'
const http = new Request()
/* config 为默认全局配置*/
http.setConfig((config) => {
	config.baseURL = baseUrl /* 根域名不同 */
	config.header = {
		...config.header,
	}
	return config
})

/* 在请求之前拦截 */
http.interceptors.request.use((config) => { // 可使用async await 做异步操作
	uni.showLoading({
		mask: true
	})
	// console.log('在请求之前拦截', config);
	config.header = {
		...config.header
	}
	return config
})

/* 在请求之后拦截 */
http.interceptors.response.use((response) => {
	uni.hideLoading()
	// console.log('在请求之后拦截', response);
	const status = response.statusCode
	if(status === 200){
		if(response.data.code === 200){
			return response.data
		}else if(response.data.code === 401){
			uni.showToast({
			     icon: 'none',
			     title: '认证失败!'
			});
			return Promise.reject('认证失败!');
		}else if(response.data.code === 500){
			uni.showToast({
			     icon: 'none',
			     title: '服务器内部错误!'
			});
			return Promise.reject('服务器内部错误!');
		}else{
			uni.showToast({
			     icon: 'none',
			     title: response.data.msg || '请求错误!',
			});
			return Promise.reject(response.data.msg || '请求错误!');
		}
	}else {
		uni.showToast({
		     icon: 'none',
		     title: '未知错误!',
		});
		return Promise.reject("未知错误!");
	}
}, (response) => {
	uni.hideLoading()
	// console.log('响应错误', response)
	const status = response.statusCode
	/*  对响应错误做点什么 (statusCode !== 200)*/
	const title = response.data ? (response.data.msg ? response.data.msg : "网络异常!" ): "网络异常!"
	uni.showToast({
	     icon: 'none',
	     title,
	});
	return Promise.reject(title)
})

export {
	http
}

@api/index.js

import { http } from '@/config/request.js'
 
// 列表
export const getList = (params) => {
	return http.get('/test/list',{ params})
}
// 新增
export const add = (data) => {
	return http.post('/test/add',data)
}
// 删除
export const del = (params) => {
	return http.delete(`/test/del/${params}`)
}
方法二:uni.request

拦截器官网 uni.addInterceptor()

http封装

import {
	urlFormat
} from '@/common/index.js'
// 拦截器配置
const httpInterceptor = {
	// 拦截前触发
	invoke(options) {
		uni.showLoading({
			mask: true
		})
		options.url = urlFormat(options.url)
		options.timeout = 10000
		options.header = {
			...options.header,
		}
		const token = uni.getStorageSync('token')
		if (token) {
			options.header['m-token'] = token
		}
	},
}

// 拦截 request 请求
uni.addInterceptor('request', httpInterceptor)
// 拦截 uploadFile 文件上传
uni.addInterceptor('uploadFile', httpInterceptor)

class Request {
	request(options) {
		return new Promise((resolve, reject) => {
			uni.request({
				...options,
				// 响应成功
				success(response) {
					uni.hideLoading()
					const status = response.statusCode
					if (status === 200) {
						if (response.data.code === 200) {
							resolve(response.data)
						} else if (response.data.code === 401) {
							// 清空缓存
							uni.clearStorageSync()
							//跳转到登录页面
							const index = getCurrentPages().length - 1
							var route = getCurrentPages()[index].$page.fullPath
							uni.reLaunch({
								url: `/pages/login/login?route=${route}`,
							});
							// uni.showToast({
							// 	icon: 'none',
							// 	title: '认证失败!'
							// });
							reject('请重新登录!');
						} else if (response.data.code === 500) {
							uni.showToast({
								icon: 'none',
								title: '服务器内部错误!'
							});
							reject('服务器内部错误!');
						} else {
							uni.showToast({
								icon: 'none',
								title: response.data.msg || '请求错误!',
							});
							reject(response.data.msg || '请求错误!');
						}
					} else {
						uni.showToast({
							icon: 'none',
							title: '未知错误!',
						});
						reject("未知错误!")
					}
				},
				// 响应失败
				fail(response) {
					uni.hideLoading()
					// console.log('响应错误', response)
					const status = response.statusCode
					/*  对响应错误做点什么 (statusCode !== 200)*/
					const title = response.data ? (response.data.msg ? response.data.msg :
						"网络异常!") : "网络异常!"
					uni.showToast({
						icon: 'none',
						title,
					});
					reject(title)
				},
			})
		})
	}
	get(url, data) {
		return this.request({
			method: 'GET',
			url,
			data,
		})
	}
	post(url, data) {
		return this.request({
			method: 'POST',
			url,
			data,
		})
	}
	put(url, data) {
		return this.request({
			method: 'PUT',
			url,
			data,
		})
	}
	delete(url, data) {
		return this.request({
			method: 'DELETE',
			url,
			data,
		})
	}
	upload(url, filePath, formData) {
		return new Promise((reslove, reject) => {
			uni.uploadFile({
				url,
				filePath,
				name: 'file', // 必填
				formData,
				// header: {},
				success: (uploadFileRes) => {
					uni.hideLoading()
					reslove(uploadFileRes.data)
				},
				fail: (e) => {
					uni.hideLoading()
					reject(e)
				},
			});
		})
	}
}

const http = new Request()

export default http

使用

import http from '@/http/request.js';

// 获取类别列表
export const test= (data) => {
    return http.get('/api',data)
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
uniapp中,可以通过封装接口来方便地进行接口调用和数据请求。下面是一个例子来说明如何封装uniapp接口。 首先,在`utils/request.js`文件中,可以定义`baseURL`作为接口请求的基地址,并导出`request`方法。该方法接收一个`options`参数,包括接口地址、请求方法、传递参数等等。在方法中,通过`uni.request`来发送请求,并返回一个Promise对象。在请求成功时,可以根据后端接口返回的数据进行相应的处理,例如判断返回结果的code值来决定是解析数据还是报错。在请求失败时,可以通过reject方法来抛出异常。 然后,在需要使用接口的地方,可以导入`request`方法,并通过调用该方法来发送请求。例如,在页面的生命周期钩子`onLoad`中调用接口,可以通过`this.$rqt.loginIn().then(res=>{ console.log(res) })`来发送请求。如果需要传递参数,可以将参数写在`loginIn`方法的参数中。建议在请求接口之前,可以使用PostMan等工具测试一下服务器是否能够正常获取数据。 最后,在`api/index.js`中,可以导入`request`方法,并使用该方法来发送请求。例如,通过`request({url: 'forum/ftype/index',method: 'post',data: {page,rows}})`来获取论坛类型。 通过以上方式,可以将uniapp接口进行封装,方便地调用和管理接口请求。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [uniapp 接口封装](https://blog.csdn.net/m0_46846526/article/details/126362687)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [uniapp封装接口](https://blog.csdn.net/zhuxiaolong1234/article/details/127816166)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值