request.js
1.34 KB
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
58
59
60
61
62
// http.js
import axios from "axios";
import { getToken } from "./local-store";
import { ElMessage } from "element-plus";
const baseURL = "http://101.43.15.205:8084"; //"http://book.xiaojinyu.games"; // 这里填入你的基础 API URL
const timeout = 15000; // 请求超时时间
const http = axios.create({
baseURL,
timeout,
headers: {
"Content-Type": "application/json",
},
});
// 请求拦截器
http.interceptors.request.use(
(config) => {
// 在发送请求之前做些什么
const TOKEN = getToken();
config.headers.Authorization = TOKEN;
if (config.method == "get") config.params = config.data;
return config;
},
(error) => {
return Promise.reject(error);
}
);
// 响应拦截器
http.interceptors.response.use(
(response) => {
// 判断是否有异常
let error = null; // 若无异常此值为null
if (response.status !== 200) {
error = Error(`Request failed with statuCode ${response.status}`);
}
if (response.data.code != 200) {
return ElMessage({ type: "error", message: response.data.msg });
}
return response.data;
},
(error) => {
// 对响应错误做点什么
return Promise.reject(error);
}
);
// 封装请求函数
const request = (method, url, data = null) => {
return http({
method,
url,
data,
});
};
export default request;