uni-app 接口封装

1.新建request文件夹,并新建config.js index.js http.js
在这里插入图片描述
2.http.js代码

import {baseURL,baseURL1} from './config.js'; 

let BASEURL = baseURL // 调整当前环境
let BASEURL2 = baseURL1 // 调整当前环境
let contentType = {
	urlencoded:'application/x-www-form-urlencoded;charset:utf-8;',
	json:'application/json',
}
/*
* 全局请求封装
* @param path 请求路径
* @param method 请求类型(GET/POST/DELETE等)
* @oaram data 请求体数据
* @oaram hasToken 是否带token
* @oaram type content-type
* @param loading 请求未完成是是否显示加载中,默认为true
*/
export default (path, method, data = {},hasToken = true,type = 'urlencoded', loading = true,) => {
	let token = undefined
	if(hasToken){
		// 获取存储token
		token = uni.getStorageSync("TOKEN");
	}
	if (loading) {
		uni.showLoading({
			title: "加载中",
			mask: true
		});
	};
	//根据token进行调用函数
	if (hasToken) {
		return tokenRequest(path, method, data,token,type, loading)
	} else {
		return noTokenRequest(path, method, data,type, loading)
	}
};

// 无token时发送请求函数
function noTokenRequest(path, method, data,type, loading) {
	return new Promise((resolve, reject) => {
		uni.request({
			url: BASEURL2 + path,
			method: method,
			data,
			header:{
				'content-type': contentType[type]
			},
			success(response) {
				// console.log('%c响应拦截:', ' background:green', response);
				/* if (response.data.code === 3001) {
					// logout()
				} */
				/* if (response.data.code !== 20) {
					uni.showToast({
						icon: "none",
						duration: 4000,
						title: response.data.msg
					});
				} */
				console.log(response.data)
				resolve(response.data);
			},
			fail(err) {
				uni.showToast({
					icon: "none",
					title: '服务响应失败'
				});
				console.error(err);
				reject(err);
			},
			complete() {
				uni.hideLoading();
			}
		});
	});
}


// 有token时发送请求函数
function tokenRequest(path, method, data,token, type, loading ) {
	return new Promise((resolve, reject) => {
		urlRequest(path, method, data, token, type, loading)
	});
}
function urlRequest(path, method, data, token, type, loading) {
	uni.request({
		url: BASEURL + path,
		method: method,
		data,
		header: {
			'content-type': contentType[type],
			"Authorization": token
		},
		success(response) {
			// console.log('%c响应拦截:', ' background:green', response);
			if (response.data.code === 40101) {
				// logout()
			}
			// console.log(response.data)
			resolve(response.data);
		},
		fail(err) {
			uni.showToast({
				icon: "none",
				title: '服务响应失败'
			});
			console.error(err);
			reject(err);
		},
		complete() {
			uni.hideLoading();
		}
	});
}

3.添加自动刷新接口

function tokenRequest(path, method, data, token, type, loading) {
	return new Promise((resolve, reject) => {
		const now = new Date().getTime();
		const expiresTime = uni.getStorageSync("tokenTime"); //token时间
		const expired = parseInt(expiresTime) - now <= 0;
		if (expired) {
			//token自动续期
			uni.request({
					url: BASEURL + "/login/automaticRenewalAccount",
					method: "post",
					data: {
						token: token
					},
					header: {
						'content-type': "application/x-www-form-urlencoded;charset:utf-8"
					},
					success(response) {
						uni.setStorageSync('token', response.data.data.token);//token
						uni.setStorageSync('tokenTime', response.data.data.expirationTime);//token时间
						urlRequest(path, method, data, response.data.data.token, type, loading)
					},
					fail(err) {
						uni.showToast({
							icon: "none",
							title: '服务响应失败'
						});
						reject(err);
					},
					complete() {
						uni.hideLoading();
					}
				})
		} else {
			urlRequest(path, method, data, token, type, loading)
		}
});
}
  1. config.js
export const baseURL = "http://xxxx"; //本地后台端口
export const baseURL1 = "http://xxxx"; //不需要token的接口

5.index.js

import request from "./http.js"

export function get (url, data, hasToken,type) {
	//return request(url, 'GET', data, hasToken, type, false)
	return request(url, 'GET', data, hasToken, 'urlencoded', false)
}
 
export function post(url, data,hasToken,type) {
	return request(url, 'POST', data, hasToken, type, false)
	//return request(url, 'POST', data, hasToken, 'json', false)
}

6.新建api文件夹
新建js文件,比如login.js,代码:

 import { get,post } from "@/request/index.js";

//需要token的接口
export const login =(data)=> post('/login', data)

//不需要token接口为false,否则为true
export const login = (data) => {
	return post("/xxx", data, false);
};

//json格式接口
export const login = (data) => {
	return post("/xxx", data, true,‘json’);
};

7.在页面中使用

import { login } from "/api/login.js";
login({id:1}).then(async res => {})

完结
根据需求修改代码。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值