-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.js
76 lines (74 loc) · 2.16 KB
/
request.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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
export default class Request {
/*
* get请求
* url:请求地址
* params:参数
* callback:回调函数
*/
static get(url, params, callback) {
if (JSON.stringify(params) !== "{}") {
let paramsArray = [];
//拼接参数
Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key]))
if (url.search(/\?/) === -1) {
url += '?' + paramsArray.join('&')
} else {
url += '&' + paramsArray.join('&')
}
}
fetch(url, { method: 'GET', })
.then((response) => response.json())
.then((responseJSON) => {
callback(responseJSON)
})
.catch((error) => {
console.log(error)
});
}
/*
* post请求
* url:请求地址
* params:参数,这里的参数格式是:{param1: 'value1',param2: 'value2'}
* callback:回调函数
*/
static postJSON(url, params, callback) {
fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(params)
})
.then((response) => response.json())
.then((responseJSON) => {
callback(responseJSON)
})
.catch((error) => {
console.log("error = " + error)
});
}
/*
* post请求
* url:请求地址
* params:参数,这里的参数要用这种格式:'key1=value1&key2=value2'
* callback:回调函数
*/
static postForm(url, params, callback) {
//fetch请求
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: params
})
.then((response) => response.json())
.then((responseJSON) => {
callback(responseJSON)
})
.catch((error) => {
console.log("error = " + error)
});
}
}