uniapp 封装请求

发布于:2024-07-04 ⋅ 阅读:(18) ⋅ 点赞:(0)

新建request文件夹 下新建index.js 和index.js 

或者创建units文件放入index.js 和api文件夹放入index.js(api.js)//看公司规范

1. index.js

// 全局请求封装
// const base_url = 'http://localhost:8080/devapi'
var base_url = process.env.NODE_ENV === 'development' ? 'http://localhost:8080/devapi' : 'http://localhost:8080/devapi'
//这个基本地址可替换成你需要的地址

// 请求超出时间
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) {
					uni.showToast({
						title: '网络异常',
						icon: "error",
						duration: 2000
					})
				} else {
					uni.showToast({
						title: '未知异常',
						duration: 2000
					})
				}
				reject(err);

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

base_url也可创建文件定义

  • .env:默认的配置文件,所有环境都会加载这个文件(如果它存在的话)。
  • .env.development:仅在开发环境(当NODE_ENV被设置为development时)加载的配置文件。
  • .env.test:仅在测试环境(当NODE_ENV被设置为test时)加载的配置文件。
  • .env.production:仅在生产环境(当NODE_ENV被设置为production时)加载的配置文件。

2. api.js

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

// 获取所有用户列表
export const getUserListApi = () => {
	return request({
		url: '/user/list',
		method: 'get',
		header: {} // 自定义
	})
}

3. 使用

	//引入
	import {
		getUserListApi
	} from '@/request/api.js'


    onLoad() {
			getUserListApi().then(res => {
				console.log(res, 'res');
			}).catch(err => {

			})
		},

下篇会解释如何处理跨域问题