# 网络请求工具
- 基于
axios 1.4.0
封装
getBaseUrl
fetch.ts
react路由外跳转
vue3路由外跳转
- 路由跳转时,路径可能不是根路径,所以需要获取当前路径
export const getBaseUrl = () => { let baseurl = `${window.location.protocol}//${window.location.host}`; if (baseurl.match(/^\//g)) { baseurl = `${window.location.protocol}//${window.location.host}${baseurl}`; } return baseurl; } export function getBasePathName() { const a = document.createElement("a"); a.href = getBaseUrl(); let rt = a.pathname.match(/^\//g) ? a.pathname : `/${a.pathname}`; rt = rt.match(/\/$/g) ? rt : `${rt}/`; return rt; }
复制成功
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 文件上传进度条
import axios, { AxiosProgressEvent } from "axios"; // 做进度条函数 const uploadProgress = (evt: AxiosProgressEvent, id: string) => { if (evt.progress && evt.total) { const percent = Math.round((evt.loaded * 100) / evt.total); setProgresses({ ...progresses, [id]: percent }); } }; const fileUpload = async (file: File) => { const url = `${getBaseUrl()}/${FILE_UPLOAD}`; const form = new FormData(); const { fileInfo, cid } = file; if (fileInfo) { form.append("file", fileInfo); const option = { method: "post", url, data: form, onUploadProgress: (event: AxiosProgressEvent) => uploadProgress(event, cid), }; try { const result = await axios(option); uploadedFilesUrl.current = { ...uploadedFilesUrl.current, [cid]: result.data.data, }; } catch (e) { setUploadFailed([...uploadFailed, cid]); } } };
复制成功
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
v1.4.16