Skip to content

Commit a9b2083

Browse files
committed
修改axios的请求封装
1 parent f7fa595 commit a9b2083

File tree

7 files changed

+165
-90
lines changed

7 files changed

+165
-90
lines changed

src/api/dev.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
export default {
2-
prefix: 'http://www.localhost:7001',
2+
prefix: 'http://localhost:4000/api/v1',
33
iamPrefix: 'https://dev.com:9002/',
44
filefix: 'http://dev.com/',
55
};

src/config/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
export const base: string = 'admin-web';
22
export const appName: string = 'admin-web';
3-
export const authToken: string = 'admin-web';
3+
export const authToken: string = 'token';
44
export const OperatedProduct = 'X-Operated-Product';
55
export const authMobile: string = '';
66
export const authEmail: string = 'auth-email';

src/main.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,12 @@ import axios from 'axios';
33
import App from './views/shared/app';
44
import router from './routers';
55
import store from './store';
6-
import { axiosConfig } from './utils';
6+
import { axiosRequest } from './utils';
77

88
Vue.config.productionTip = false;
99

10-
axiosConfig();
11-
Vue.prototype.axios = axios;
10+
// 初始化请求的封装函数
11+
axiosRequest.init();
1212

1313
// 配置element-ui组件库
1414
import ElementUI from 'element-ui';

src/utils/axios-config.ts

Lines changed: 0 additions & 73 deletions
This file was deleted.

src/utils/axios-request.ts

Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
/*
2+
* @Description:对axios请求的封装
3+
* @Author: 水痕
4+
* @Github: https://github.com/kuangshp
5+
* @Email: 332904234@qq.com
6+
* @Company:
7+
* @Date: 2019-08-16 16:57:42
8+
* @LastEditors: 水痕
9+
* @LastEditTime: 2019-08-21 12:23:41
10+
*/
11+
12+
import axios from 'axios';
13+
import { storage } from './storage';
14+
import { prefix, iamPrefix } from '@/api';
15+
import { authMobile, authToken } from '@/config';
16+
import routers from '../routers';
17+
18+
class AxiosRequest {
19+
public init() {
20+
axios.defaults.headers.post['Content-Type'] =
21+
'application/x-www-form-urlencoded;charset=UTF-8';
22+
axios.defaults.timeout = 60 * 1000;
23+
// 拦截请求的
24+
axios.interceptors.request.use(
25+
(config: { [propsName: string]: any }) => this.request(config),
26+
(rejection: { data: any }) => this.requestError(rejection),
27+
);
28+
// 拦截响应
29+
axios.interceptors.response.use(
30+
(res: any) => this.response(res),
31+
(error: any) => this.responseError(error),
32+
);
33+
}
34+
35+
private request(config: { [propsName: string]: any }) {
36+
// 配置请求头
37+
config.headers['X-Origin'] = 'admin-web';
38+
config.headers[authToken] = storage.getItem(authToken);
39+
// config.headers[authMobile] = storage.getItem(authMobile);
40+
// 处理请求地址
41+
const input = config.url;
42+
if (this.isHttpUrl(input)) {
43+
config.url = input;
44+
} else if (this.isIamUrl(input)) {
45+
config.url = `${iamPrefix}${input}`;
46+
} else {
47+
config.url = `${prefix}${input}`;
48+
}
49+
return config;
50+
}
51+
52+
private requestError(rejection: { data: any }) {
53+
return this.useOrigin(rejection)
54+
? Promise.reject(rejection)
55+
: Promise.reject(rejection.data);
56+
}
57+
58+
private response(res: any) {
59+
return this.isPlainRequest(res.config.url) || this.useOrigin(res)
60+
? res
61+
: res.data;
62+
}
63+
64+
private responseError(error: any) {
65+
if (error.response && error.response.status) {
66+
let $path;
67+
let $message;
68+
let $errorInfo;
69+
if (error.response.data) {
70+
const { path, message, data } = error.response.data;
71+
$path = path;
72+
$message = message;
73+
$errorInfo = Array.isArray(data.error)
74+
? data.error.join(',')
75+
: data.error;
76+
}
77+
switch (error.response.status) {
78+
case 400:
79+
console.log(`错误的请求:${$path}-${$errorInfo}`);
80+
break;
81+
// 401: 未登录
82+
// 未登录则跳转登录页面,并携带当前页面的路径
83+
// 在登录成功后返回当前页面,这一步需要在登录页操作。
84+
case 401:
85+
routers.replace({
86+
path: '/login',
87+
query: {
88+
redirect: routers.currentRoute.fullPath,
89+
},
90+
});
91+
break;
92+
93+
// 403 token过期
94+
// 登录过期对用户进行提示
95+
// 清除本地token和清空vuex中token对象
96+
// 跳转登录页面
97+
case 403:
98+
console.log('登录过期,请重新登录');
99+
// 清除全部的缓存数据
100+
window.localStorage.clear();
101+
// store.commit('loginSuccess', null);
102+
// 跳转登录页面,并将要浏览的页面fullPath传过去,登录成功后跳转需要访问的页面
103+
setTimeout(() => {
104+
routers.replace({
105+
path: '/login',
106+
query: {
107+
redirect: routers.currentRoute.fullPath,
108+
},
109+
});
110+
}, 1000);
111+
break;
112+
113+
// 404请求不存在
114+
case 404:
115+
console.log('网络请求不存在');
116+
break;
117+
// 其他错误,直接抛出错误提示
118+
default:
119+
console.log('我也不知道是什么错误');
120+
break;
121+
}
122+
}
123+
return error.response
124+
? Promise.reject(error.response)
125+
: Promise.reject(error);
126+
}
127+
128+
private isHttpUrl(input: string) {
129+
return /^https?:\/\//.test(input);
130+
}
131+
132+
// 判断是不是图片请求
133+
private isIamUrl(input: string) {
134+
return /^(sso|iam|iam-.*)\//.test(input);
135+
}
136+
137+
private isPlainRequest(input: string) {
138+
return /\.(html?|xml|txt)$/.test(input);
139+
}
140+
141+
private useOrigin(res: any) {
142+
return res.config.useOrigin;
143+
}
144+
}
145+
146+
export const axiosRequest = new AxiosRequest();

src/utils/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
export * from './storage';
22
export * from './auth';
33
export * from './set-title';
4-
export * from './axios-config';
4+
export * from './axios-request';
55
export * from './data-type';

src/views/shared/login/Login.vue

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@
4444

4545
<script lang="ts">
4646
import { Component, Vue, Provide } from 'vue-property-decorator';
47-
import { OperatedProduct } from '@/config';
47+
import { authToken } from '@/config';
4848
import { storage } from '@/utils';
4949
import axios from 'axios';
5050
@@ -55,18 +55,20 @@ export default class Login extends Vue {
5555
password: '',
5656
};
5757
private submitForm(formType: string): void {
58-
(this.$refs[formType] as any).validate((valid: boolean) => {
58+
(this.$refs[formType] as any).validate(async (valid: boolean) => {
5959
if (valid) {
60-
axios.post('/api/v1/user/login', { userName: this.loginForm.email, password: this.loginForm.password })
61-
.then((data: any) => {
62-
console.log(data);
63-
});
64-
// 设置本地存储
65-
storage.setItem(OperatedProduct, this.loginForm.email);
66-
if (this.$route.query.backUrl) {
67-
this.$router.push((this.$route.query as any).backUrl);
60+
const postData = { name: this.loginForm.email, password: this.loginForm.password };
61+
const { code, result: { data: { token } }, message } = await axios.post('/login', postData);
62+
if (code === 0) {
63+
// 设置本地存储
64+
storage.setItem(authToken, token);
65+
if (this.$route.query.backUrl) {
66+
this.$router.push((this.$route.query as any).backUrl);
67+
} else {
68+
this.$router.push('/');
69+
}
6870
} else {
69-
this.$router.push('/');
71+
console.log(message);
7072
}
7173
} else {
7274
return false;

0 commit comments

Comments
 (0)