欢迎点击领取 -《前端面试题进阶指南》:前端登顶之巅-最全面的前端知识点梳理总结
*分享一个使用比较久的
自带的微信小程序请求及框架类请求,书写比较繁琐;为了简写方便和全局处理封装的请求,因此我们对Taro.request请求二次封装和uni.request请求二次封装;以及包含常用的工具库封装,包含路由的跳转方法等
import Taro from '@tarojs/taro'
import api from "../api/login";
const BASE_URL = 'https://www.123fe.net'
/**
* @param {Object} props
* @description 针对搜索值做统一处理
*/
const convertParams = (props) => {
const newParams = {};
for (const index in props) {
const item = props[index];
const type = typeof item;
if (item || item === false || item === 0) {
if (item && type === 'string') {
newParams[index] = item.replace(/\s/g, '');
}
if (Object.prototype.toString.call(item) === '[object Object]') {
newParams[index] = convertParams(item)
} else {
newParams[index] = item;
}
}
}
return newParams;
};
interface configData {
contentType?: string
}
const codeMessage = {
200: '服务器成功返回请求的数据。',
201: '新建或修改数据成功。',
202: '一个请求已经进入后台排队(异步任务)。',
204: '删除数据成功。',
400: '发出的请求有错误。',
401: '用户没有权限(令牌、用户名、密码错误)。',
403: '用户得到授权,但是访问是被禁止的。',
404: '请求资源不存在。',
406: '请求的格式不可得。',
410: '请求的资源被永久删除,且不会再得到的。',
422: '当创建一个对象时,发生一个验证错误。',
500: '服务器发生错误,请检查服务器。',
502: '网关错误。',
503: '服务不可用,服务器暂时过载或维护。',
504: '网关超时。',
};
const baseOptions = (url: string, params: object = {}, method = 'get', config: configData = {}) => {
const { contentType } = config
Taro.showLoading({ title: "", mask: false });
const option: any = {
url: BASE_URL + url,
data: params,
method: method,
timeout: 10000,
header: { 'content-type': contentType || 'application/json;charset=UTF-8', Authorization: Taro.getStorageSync('token') },
success(response) {
Taro.hideLoading();
const data = response.data;
if (data.code === 200) return data
if (data.code === 403) return removeSorage()
Taro.showToast({
icon: 'none',
duration: 3000,
title: data.msg || '',
})
return data
},
error(err) {
Taro.hideLoading();
if (err.statusCode === 403) return removeSorage()
Taro.showToast({
icon: 'none',
duration: 3000,
title: codeMessage[err.statusCode] || '',
})
return Promise.reject(err)
}
}
return Taro.request(option)
}
const request = async (url: string, params: object = {}, method = 'get', config?) => {
params = convertParams(params)
try {
const res = await baseOptions(url, params, method, config)
return res.data
} catch (err) {
throw new Error(err)
}
}
// 获取当前用户个人信息
const getUserInfo = async () => {
const res = await api.userinfo();
if (res.code !== 200) return false;
const data = res.data
if (!data.vipType) {
Taro.setStorageSync("vipTypeOpen", true);
}
Taro.setStorageSync("userInfo", data);
return true
};
const removeSorage = () => {
Taro.removeStorage({ key: 'userInfo' })
Taro.removeStorage({ key: 'token' })
location.reload()
}
export { request, getUserInfo, removeSorage }
interface requestInt {
url: string,
method: 'GET' | 'POST' | 'DELETE' | 'PUT',
params: string | object | ArrayBuffer,
options?: any,
}
/**
* @param {Object} props
* @description 针对搜索值做统一处理
*/
const convertParams = (props) => {
const newParams = {};
for (const index in props) {
const item = props[index];
const type = typeof item;
if (item || item === false || item === 0) {
if (item && type === 'string') {
newParams[index] = item.replace(/\s/g, '');
}
if (Object.prototype.toString.call(item) === '[object Object]') {
newParams[index] = convertParams(item)
} else {
newParams[index] = item;
}
}
}
return newParams;
};
const codeMessage = {
200: '服务器成功返回请求的数据。',
201: '新建或修改数据成功。',
202: '一个请求已经进入后台排队(异步任务)。',
204: '删除数据成功。',
400: '发出的请求有错误。',
401: '用户没有权限(令牌、用户名、密码错误)。',
403: '用户得到授权,但是访问是被禁止的。',
404: '请求资源不存在。',
406: '请求的格式不可得。',
410: '请求的资源被永久删除,且不会再得到的。',
422: '当创建一个对象时,发生一个验证错误。',
500: '服务器发生错误,请检查服务器。',
502: '网关错误。',
503: '服务不可用,服务器暂时过载或维护。',
504: '网关超时。',
};
const request = (baseOptions: requestInt) => {
const { url, method, params, options } = baseOptions
const { contentType } = options || {}
uni.showLoading({ title: '加载中...', mask: true });
return new Promise<any>((resolve, reject) => {
uni.request({
url: `${import.meta.env.VITE_BASE_API}${url}`,
method,
data: convertParams(params),
header: {
'content-type': contentType || 'application/json;charset=UTF-8',
Authorization: 'Bearer ' + uni.getStorageSync('token')
},
success: (res: any) => {
uni.hideLoading();
switch (res.statusCode) {
case 200:
resolve(res.data)
break;
default:
uni.showModal({
title: '温馨提示',
content: '未知异常,请稍后在试!',
showCancel: false,
});
reject(res)
}
},
fail: (err: any) => {
uni.hideLoading();
uni.showToast({
icon: 'none',
duration: 3000,
title: codeMessage[err.statusCode] || '',
})
reject(err)
}
})
})
}
export default request
// 创建的api.js文件
import { request } from '../utils/service';
const api = {
login: () => '/api/login'
}
const userLogin = (params = {}) => request(api.login(), params, 'post')
export default { userLogin }
uni-app同类型做下引用的替换,这里就不重复写了;
import Taro from '@tarojs/taro'
// 打开新页面并跳转
function navigateTo(url, params?) {
const paramsStr = handleParams(params)
Taro.navigateTo({
url: url + paramsStr
})
}
// 关闭当前页面并跳转新的页面
function redirectTo(url, params?) {
const paramsStr = handleParams(params)
Taro.redirectTo({
url: url + paramsStr
})
}
// 返回上级页面
function navBack(delta) {
let currentDelta = delta
if (!delta || typeof delta !== 'number') {
currentDelta = 1
}
Taro.navigateBack({ delta: currentDelta }).then(r => r)
}
// 关闭所有页面并跳转到tabBar页面
function switchTab(url) {
Taro.switchTab({
url: url
}).then(r => r)
}
// 参数转换拼接
function handleParams(params) {
let paramsStr = ''
if (params && typeof params === 'object') {
const keys = Object.keys(params) || []
if (keys && keys.length) {
keys.forEach((key, index) => {
if (index === 0) {
paramsStr += `?${key}=${params[key]}`
} else {
paramsStr += `&${key}=${params[key]}`
}
})
}
}
return paramsStr
}
export {
navigateTo,
redirectTo,
navBack,
switchTab,
handleParams,
}