第09节:封装get请求模式下uri参数自动拼接函数 编写user接口

摘要:/*** 参数转url字符串* @param params 参数* @param url 需要拼接参数的地址*//**{k1: 'v1',k2: 'v2',}http://test.com?k1=v1&k2=v2http://test.com?k1=v1&k2

/*** 参数转url字符串* @param params 参数* @param url 需要拼接参数的地址*//**{k1: 'v1',k2: 'v2',}http://test.com?k1=v1&k2=v2http://test.com?k1=v1&k2[sk1]=sv1&k2[sk2]=sv2*/exportfunction toURLSearch(params, url) {if (typeof params !== 'object' || params == null) {return '';}const result = transformParams(params).map((d) => `${encodeURIComponent(d[0])}=${encodeURIComponent(d[1])}`).join('&');if (!url) {return result;}return (url.includes('?') ? `${url}&` : `${url}?`) + result;}/*** get请求处理数组和对象类型参数,递归处理* @param params 参数*//**{k1:'v1',k2:{sk1: 'sv1',sk2: 'sv2',}}// [['k1', 'v1'],['k2[sk1]', 'sv1'], ['k2[sk2]', 'sv2']]*///递归执行getObjectParamsArrayexport function transformParams(params) {const result = ;if (params != null && typeof params === 'object') {Object.keys(params).forEach((key) => {const value = params[key];if (value != null && value !== '') {if (typeof value === 'object' && !isBlobFile(value)) {getObjectParamsArray(value).forEach((item) => {result.push([`${key}${item[0]}`, item[1]]);});} else {result.push([key, value]);}}});}return result;}/*** 对象转参数数组* @param obj 对象*//**{k1:'v1',k2:{sk1: 'sv1',sk2: 'sv2',}}// [['[k1]', 'v1'],['[k2][sk1]', 'sv1'], ['[k2][sk2]', 'sv2']]*/export function getObjectParamsArray(obj) {const result = ;Object.keys(obj).forEach((key) => {const value = obj[key];if (value != null && value !== '') {const name = `[${key}]`;if (typeof value === 'object' && !isBlobFile(value)) {getObjectParamsArray(value).forEach((item) => {result.push([`${name}${item[0]}`, item[1]]);});} else {result.push([name, value]);}}});return result;}/*** 判断是否是文件* @param obj 对象*///obj = new File('test.txt') or new File({type:'text/plain'}) //falseexport function isBlobFile(obj) {return obj != null && (obj instanceof Blob || obj instanceof File);} /*** axios请求拦截*/service.interceptors.request.use((config) => {//1.获取token用做验证const token = getTokenif (token && config.headers) {config.headers[TOKEN_CACHE_NAME] = token}//2.过滤get请求并格式化//2.1这里有个坑,所有api为get的请求中,params 键名不能少if (config.method === 'get' && config.params) {//2.2在接口{ params: data }的 data 最终都为 {user: 'a', password: 'b'}config.url = toURLSearch(config.params, config.url);//2.3当拼接完成以后,清除params对象config.params = {};}//3.返回configreturn config}, (error) => {//抛出错误return Promise.reject(error)}); import service from '@/utils/request.js'export const pageUser = async (data) => {//console.log(data)const res = await service.get('/api/sys/user/page', { params: data});if (res.data.code === 200) {return res.data.data}return Promise.reject(new Error(res.data.message))}

来源:科技虫祥

相关推荐