【uniapp】带你优雅的封装uniapp的request请求

封装前的准备

先在项目目录上右键 - 新建目录request(用于存放封装的API请求文件),并至少创建两个js文件

  • index.js用于封装get、post请求,接收参数并返回数据
  • api.js用于封装后台接口,便于页面调用和后期维护(可以是多个,看自己的模块化分)

接下来直接上干货,不啰嗦

1. index.js:封装get、post请求,接收参数并返回数据
// 全局请求封装
const base_url = 'http://localhost:996'
// 请求超出时间
const timeout = 5000

// 需要修改token,和根据实际修改请求头
export default (params) => {
	let url = params.url;
	let method = params.method || "get";
	let data = params.data || {};
	let header = {
		'Blade-Auth': uni.getStorageSync('token') || '',
		'Content-Type': 'application/json;charset=UTF-8',
		'Authorization': 'Basic c2FiZXI6c2FiZXJfc2VjcmV0',
		'Tenant-Id': uni.getStorageSync('tenantId') || 'xxx', // avue配置相关
		...params.header
	}
	if (method == "post") {
		header = {
			'Content-Type': 'application/json'
		};
	}
	return new Promise((resolve, reject) => {
		uni.request({
			url: base_url + url,
			method: method,
			header: header,
			data: data,
            timeout ,
			success(response) {
				const res = response
				// 根据返回的状态码做出对应的操作
				//获取成功
				// console.log(res.statusCode);
				if (res.statusCode == 200) {
					resolve(res.data);
				} else {
					uni.clearStorageSync()
					switch (res.statusCode) {
						case 401:
							uni.showModal({
								title: "提示",
								content: "请登录",
								showCancel: false,
								success() {
									setTimeout(() => {
										uni.navigateTo({
											url: "/pages/login/index",
										})
									}, 1000);
								},
							});
							break;
						case 404:
							uni.showToast({
								title: '请求地址不存在...',
								duration: 2000,
							})
							break;
						default:
							uni.showToast({
								title: '请重试...',
								duration: 2000,
							})
							break;
					}
				}
			},
			fail(err) {
				console.log(err)
				if (err.errMsg.indexOf('request:fail') !== -1) {
					wx.showToast({
						title: '网络异常',
						icon: "error",
						duration: 2000
					})
				} else {
					wx.showToast({
						title: '未知异常',
						duration: 2000
					})
				}
				reject(err);

			},
			complete() {
				// 不管成功还是失败都会执行
				uni.hideLoading();
				uni.hideToast();
			}
		});
	}).catch(() => {});
};

 2. api.js 封装后台接口,便于页面调用和后期维护

// 引入 request 文件
import request from './index.js'

// 分页查询学习列表
export const pageStudyInfo = (params) => {
	return request({
		url: '/study/studyInfo/page',
		method: 'get',
		data: params,
        header: {} // 自定义
	})
}
// 获取学习列表详细信息
export const studyInfoById = (id) => {
	return request({
		url: `/study/studyInfo/${id}`,
		method: 'get',
	})
}

 3. 页面调用

import { pageStudyInfo } from '@/request/api.js'

// 获取学习列表详情信息
pageStudyInfo (data).then((res) => {
  console.log('成功', res);  
}).catch((err) => { 
  console.error('失败', err);
});

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值