index.js
1.67 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
/*
* @Descripttion: 定义一个Request类,用于封装请求高德地图API的方法
* @version: 1.0.0
* @Author: limin
* @Date: 2023-07-04 17:25:31
* @LastEditors: limin
* @LastEditTime: 2023-08-17 15:10:36
* @FilePath: \glsx-common-sdk\src\request\index.js
*/
import wxRequest from './wx'
import webRequest from './web'
import createSign from './sign'
import RequestMethods from './requestMethods'
import { response as res } from './default'
class Request {
// 构造函数,接收key和secret作为参数,如果没有传入,则使用默认值
constructor({ response = res, request = response, headers = {}, alert, isMP } = {}) {
this.response = response
this.request = request
this.headers = headers
this.alert = alert
this.isMiniprogram = +isMP
}
/**封装的GET方法 */
get(data, noSignAttr) {
// 调用request方法,传入请求方式为GET,请求路径为method,请求数据为data
return this.fetch({ method: RequestMethods.GET, data, noSignAttr })
}
post(data, noSignAttr) {
// 调用request方法,传入请求方式为GET,请求路径为method,请求数据为data
return this.fetch({ method: RequestMethods.POST, data, noSignAttr })
}
/**封装的请求方法 */
fetch({ data, noSignAttr = [], method = RequestMethods.POST }) {
// 调用getSign方法,传入请求数据和请求路径,得到签名
const signData = createSign(data, this.request.secret, noSignAttr, this.request.signWay)
const options = {
obj: signData,
method,
baseUrl: this.request.baseUrl,
headers: this.headers
}
return [webRequest, wxRequest][this.isMiniprogram](options)
}
}
export default Request