Skip to content

Commit 2f0973f

Browse files
committed
feat: http request
1 parent 5623092 commit 2f0973f

File tree

4 files changed

+92
-0
lines changed

4 files changed

+92
-0
lines changed

package.json

+1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
"@babel/core": "^7.12.10",
1414
"@babel/plugin-transform-runtime": "^7.12.10",
1515
"@babel/preset-env": "^7.12.11",
16+
"axios": "^0.21.1",
1617
"babel-core": "^7.0.0-bridge.0",
1718
"babel-loader": "^7.1.5",
1819
"babel-plugin-transform-runtime": "^6.23.0",

src/api/index.js

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import * as user from './user';
2+
3+
export default {
4+
...user,
5+
}

src/api/user.js

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import request from '../util/request';
2+
3+
export const login = data => request.post('/api/login', data)

src/util/request.js

+83
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
import axios from 'axios';
2+
3+
class Request {
4+
constructor() {
5+
const codeMessage = {
6+
'服务器成功返回请求的数据。': 200,
7+
'新建或修改数据成功。': 201,
8+
'一个请求已经进入后台排队(异步任务)。' : 202,
9+
'删除数据成功。' : 204,
10+
'发出的请求有错误,服务器没有进行新建或修改数据的操作。' : 400,
11+
'用户没有权限(令牌、用户名、密码错误)。' : 401,
12+
'用户得到授权,但是访问是被禁止的。' : 403,
13+
'发出的请求针对的是不存在的记录,服务器没有进行操作。' : 404,
14+
'请求的格式不可得。' : 406,
15+
'请求的资源被永久删除,且不会再得到的。' : 410,
16+
'当创建一个对象时,发生一个验证错误。' : 422,
17+
'服务器发生错误,请检查服务器。' : 500,
18+
'网关错误。' : 502,
19+
'服务不可用,服务器暂时过载或维护。' : 503,
20+
'网关超时。' : 504,
21+
};
22+
23+
//http request 拦截器
24+
axios.interceptors.request.use(
25+
config => {
26+
// const token = getCookie('名称');注意使用的时候需要引入cookie方法,推荐js-cookie
27+
config.data = JSON.stringify(config.data);
28+
config.headers = {
29+
'Content-Type': 'application/x-www-form-urlencoded'
30+
}
31+
// if(token){
32+
// config.params = {'token':token}
33+
// }
34+
return config;
35+
}
36+
);
37+
//http response 拦截器
38+
axios.interceptors.response.use(
39+
response => {
40+
console.log(response)
41+
if (response.data.errCode == 2) {
42+
// router.push({
43+
// path: "/login",
44+
// querry: { redirect: router.currentRoute.fullPath }//从哪个页面跳转
45+
// })
46+
}
47+
return response;
48+
},
49+
error => {
50+
if (error.response.status === 404) {
51+
window.location.href = '/#/404';
52+
}
53+
if (error.response.status === 401) {
54+
// window.location.href = '/#/login';
55+
}
56+
return Promise.reject({
57+
status: error.response.status,
58+
statusText: error.response.statusText,
59+
descript: codeMessage[error.response.status] || '服务异常',
60+
})
61+
}
62+
)
63+
}
64+
65+
get(url, params = {}) {
66+
return axios.get(url, params);
67+
}
68+
69+
post(url, data = {}) {
70+
return axios.post(url, data);
71+
}
72+
73+
put(url, data = {}) {
74+
return axios.put(url, data);
75+
}
76+
77+
delete(url) {
78+
return axios.delete(url);
79+
}
80+
}
81+
82+
83+
export default new Request();

0 commit comments

Comments
 (0)