文章目录
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117

function messageError(message,title){
console.log(message,title)
}
/**
* 状态检查
*/
export function checkStatus(response) {
if (response && response.status >= 200 && response.status < 400) {
return response;
}
if (response && response.status === 401) {
messageError('会话超时,请重新登录','会话超时,请重新登录')
if(typeof window !== "undefined") {
sessionStorage.clear();
}
}
if (!response) {
messageError('您的网络发生异常,无法连接服务器','网络异常')
} else {
const { status, url, statusText } = response;
messageError(statusText,`请求错误 ${status}: ${url}`)
}
}

var access_token = '';
if(typeof window !== "undefined") {
access_token = sessionStorage.getItem('token') ''
}

const headerParams = {
token: access_token,
}

/**
* 请求接口封装
*/
export async function request(url,headers) {
try{
const fetchResponse = await fetch(url, headers);
const response = checkStatus(fetchResponse);
if(response){
return response.json();
}
}catch(err){
messageError(url,'请求失败')
}
}

/**
* post
* @param url
* @param params
* @param headers
*/
export function post(url,body,headers){
return request(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
...headerParams,
...headers,
},
body: JSON.stringify(body),
});
}

/**
* get
* @param url 请求URL
* @param params 请求参数
* @param headers 额外HTTP头
*/
export function get(url, params, headers){
if (params) {
const paramsArray = [];
//拼接参数
Object.keys(params).forEach(key =>
paramsArray.push(key + '=' + params[key]),
);
if (url.search(/\?/) === -1) {
url += '?' + paramsArray.join('&');
} else {
url += '&' + paramsArray.join('&');
}
}

return request(url, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
...headerParams,
...headers,
},
});
}

/**
* put
* @param url 请求URL
* @param body 正文内容
* @param headers 额外请求头
*/
export function put(url,body,headers){
return request(url, {
method: 'PUT',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
...headerParams,
...headers,
},
body: JSON.stringify(body),
});
}
文章目录