Request类的构造函数
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
class Request {
constructor(options) {
this.method = options.method || 'GET'
this.host = options.host
this.path = options.path || '/'
this.port = options.port || 80
this.headers = options.headers || {}
this.body = options.body || {}

if (!this.headers['Content-Type']) {
this.headers['Content-Type'] = 'application/x-www-form-urlencoded'
}

if (this.headers['Content-Type'] === 'text/json') {
this.bodyText = JSON.stringify(this.body)
} else if (
this.headers['Content-Type'] === 'application/x-www-form-urlencoded'
) {
this.bodyText = Object.keys(this.body)
.map((k) => `${k}=${encodeURIComponent(this.body[k])}`)
.join('&')
}

this.headers['Content-Length'] = this.bodyText.length
}
}