快速获取路由参数
地址示例:const url = 'https://www.baidu.com/?why=baidu&age=18'
首先将url通过?
号分割,取下表[1]的值
url.split('?')[1]
// why=baidu&age=18
第二步 将参数&
替换成 ","
符号
url.split('?')[1].replace(/&/g, '","')
// why=baidu","age=18
第三步 将 =
号改为 :
号,此时已经基本能看到JSON格式
url.split('?')[1].replace(/&/g, '","').replace(/=/g, '":"')
// why:baidu","age:18
最后,将最外层使用"
包括住,并通过JSON.parse即可转化为对象类型
完整代码
const getParams = URL => JSON.parse(`{"${URL.split('?')[1].replace(/&/g, '","').replace(/=/g, '":"')}"}`)
console.log(getParams(url));
// {"why:baidu","age:18"}
计算两个日期之差
const dayDiff = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000);
dayDiff(new Date("2021-10-21"), new Date("2022-02-12"))
字符串替换
const render = (template, data) => {
if (!data) return template;
if (Array.isArray(data)) {
for(let i = 0; i < data.length; i++)
template = template.replace(new RegExp('\\{' + i + '\\}', 'g'), data[i]);
} else {
for (let key in data) {
template = template.replace(new RegExp('\\{' + key + '\\}', 'g'), data[key]);
}
}
return template;
}
const temp = '我的名字是{name}, 我的年龄是{age}';
const temp1 = '我的名字是{0}, 我的年龄是{1}';
const newTemp = render(temp, {name: 'gzc'});
const newTemp1 = render(temp1, ['gzc']);
console.log(newTemp)
console.log(newTemp1)
下载文件
const res = await request(...);
const blob = new Blob([res]);
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
document.body.appendChild(a); //兼容火狐,将a标签添加到body当中
a.href = url;
a.download = decodeURI('模板.xlsx');
a.target = '_blank'; // a标签增加target属性
a.click();
a.remove(); //移除a标签
window.URL.revokeObjectURL(url);
umi http请求封装
/*
* @Author: 郭智成
* @Date: 2022-07-22 11:35:10
* @FilePath: /car_mgr_web/src/request/index.ts
* @Description: 网络请求
*/
import { extend } from 'umi-request';
import { codeMessage, download, errorHandler, resolveBlob } from './config';
import { getToken } from '@/utils/storage';
import { notification } from 'antd';
import { history } from 'umi';
type RequestApi = {
url: string,
method: 'GET' | 'POST' | 'PUT' | 'DELETE',
options?: Record<string, any>,
}
interface RequestParams {
/** 需要放在body内传递的参数 */
data?: Record<string, any>,
/** 拼接在url地址后的参数 */
params?: Record<string, any>,
/** 扩展字段 */
option?: Record<string, any>,
}
interface FormData {
/** 要上传文件资源的路径。 */
filePath: string
/** 文件对应的参数名 */
fileKey: string
[key: string]: any
}
const { NODE_ENV } = process.env;
const BASE_URL = NODE_ENV === 'development' ? '' : location.origin;
const timeout = 10000;
const apiBasePath = '/api/plat';
// zip配置
const mimeMap = {
xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
zip: 'application/zip',
};
function createClient () {
/** 配置request请求时的默认参数 */
return extend({
errorHandler, // 默认错误处理
// credentials: 'include', // 默认请求是否带上cookie
prefix: apiBasePath,
});
}
export const request = createClient();
/** 请求拦截 */
request.interceptors.request.use((url: string, options: any) => {
const token = getToken();
options.headers = {
...options.headers,
Authorization: `Bearer ${token}`,
};
return { url: BASE_URL + url, options };
});
/** 响应拦截 */
request.interceptors.response.use(async (response: Response) => {
let notificationOpt: null | { message: string, description: string } = null;
const { status, url } = response || {};
if (status == 200) {
let data = await response.clone().json();
const { respCode, respMsg, success } = data;
if (success) return response;
const errorText = respMsg || codeMessage[respCode];
if (respCode === '401') {
history.replace('/login')
}
console.error(`${errorText} code: ${respCode}: ${url}`);
notificationOpt = {
message: `${errorText} code: ${respCode}: ${url}`,
description: '请求错误',
};
}
if (!response) {
notificationOpt = {
message: '网络开小差了,无法连接服务器',
description: '请求错误',
};
}
!!notificationOpt && notification.error(notificationOpt);
});
/** 统一请求接口 */
const requestApi = ({
url,
method,
options = {}
}: RequestApi) => {
return request<any>(url, {
method,
timeout,
...options,
});
}
/**
* get请求
* @param param1 params 请求参数
* @param param1 option 其余扩展参数
* @returns
*/
const GET = (url: string, requestParams?: RequestParams) => {
const { params, option = {} } = requestParams || {};
const options = { params, ...option };
return requestApi({ url, method: 'GET', options });
}
/**
* post请求
* @param requestParams data 放入body的参数
* @param requestParams params 请求参数
* @param requestParams option 其余扩展参数
* @returns
*/
const POST = <T>(url: string, data?: Record<string, any>, requestParams?: RequestParams): Promise<T> => {
const {
params,
option = {
headers: {
'Content-Type': 'application/json',
},
}
} = requestParams || {};
const options = { data, params, ...option };
return requestApi({ url, method: 'POST', options });
}
/**
* delete请求
* @param param1 params 请求参数
* @param param1 option 其余扩展参数
* @returns
*/
const DELETE = (url: string, config?: RequestParams) => {
const {
option = {
headers: {
'Content-Type': 'application/json',
},
}
} = config || {};
const options = { ...option };
return requestApi({ url, method: 'DELETE', options });
}
/**
* put请求
* @param data body参数
* @param params 请求参数
* @param option 其余扩展参数
* @returns
*/
const PUT = (url: string, requestParams: RequestParams) => {
const { data, params, option = {} } = requestParams;
const options = { data, params, ...option };
return requestApi({ url, method: 'PUT', options });
}
/**
* 上传请求
* @param data 需要上传的文件信息
* @returns
*/
const upload = (url: string, data: FormData) => {
const options = {
data,
headers: {
'Content-Type': 'multipart/form-data',
},
};
return requestApi({ url, method: 'POST', options });
}
/** 下载zip */
const downLoadZip = (url: string) => {
requestApi({
url,
method: 'GET',
options: {
responseType: 'blob',
getResponse: true,
}
}).then((res) => {
resolveBlob(res, mimeMap.zip);
});
}
/** 下载文件 */
const downLoadFile = async(url: string, params: any, fileName: string) => {
return requestApi({
url,
method: 'POST',
options: {params, responseType: 'blob'}
}).then((data) => {
download(data, fileName);
});
}
const pages = <T = any>(url: string, { current = 1, pageSize = 10, ...others } = {}): Promise<PageResult<T>> => {
return POST(url, { currentPage: current, pageSize, ...others })
.then((res: any) => {
const { total, size, current, pages, records } = res?.data as any;
return {
success: true,
total,
pages,
size,
current,
data: records,
}
})
}
export {
GET,
POST,
DELETE,
PUT,
upload,
downLoadFile,
downLoadZip,
pages,
};
type PageResult<T> = {
success: boolean,
/** 总记录数 */
total: number,
/** 总页数 */
pages: number,
/** 每页条数 */
size: number
/** 当前页数 */
current: number
/** 记录数组 */
data: T[]
}