1、在src下创建一个Https的文件
在api.js中
复制代码
1
2
3
4
5
6
7
8
9
10import service from './index'; export default { //写请求 login({ username, password }: { username: string, password: string }) { }, getDate({pagenum,pagesize,query}:{pagenum:number|string,pagesize:number|string,query?:string}){ } }
index.js
复制代码
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58import axios, { AxiosInstance, AxiosRequestConfig, AxiosError, AxiosResponse } from 'axios' import nProgress from 'nprogress' import nprogress from 'nprogress'; const service: AxiosInstance = axios.create({ baseURL: 'http://v.juhe.cn/', //基础路径 timeout: 10000 }) // 请求拦截: 每一次发请求都会做的事情 service.interceptors.request.use((config: AxiosRequestConfig): AxiosRequestConfig => { nProgress.start() let token = localStorage.getItem('token') config.headers['Authorization'] = token return config }, (err: AxiosError) => { console.log(err) return Promise.reject(err) }) //响应拦截 service.interceptors.response.use((res: AxiosResponse): AxiosResponse => { return res.data }, (err: AxiosError) => { if (err.response && err.response.status) { nprogress.done() console.log(err) // 错误请求的状态码 let status = err.response.status // if (status === 400) { // Message.error('参数错误') // } // if (status === 401) { // Message.error('登录过期,请重新登录') // } // if (status === 403) { // Message.error('没有权限') // } // if (status === 404) { // Message.error('接口路径错误') // } // if (status === 500) { // Message.error('服务器出错') // } // if (status === 503) { // Message.error('服务器在维护') // } // } return Promise.reject(err) } }) export default service
在router.js 加入
复制代码
1
2
3
4
5
6
7
8const isPro: boolean = process.env.NODE_ENV === 'production' const router = createRouter({ //history路由模式 history: isPro ? createWebHashHistory(process.env.Base_URL) : createWebHistory(process.env.BASE_URL), routes });
最后
以上就是贪玩花卷最近收集整理的关于vue3 封装api的全部内容,更多相关vue3内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复