-
Notifications
You must be signed in to change notification settings - Fork 64
Expand file tree
/
Copy pathrequest.js
More file actions
285 lines (247 loc) · 7.03 KB
/
request.js
File metadata and controls
285 lines (247 loc) · 7.03 KB
Edit and raw actions
OlderNewer
1
// var Base64 = require('Base64')
2
var capability = require('./capability')
3
var inherits = require('inherits')
4
var response = require('./response')
5
var stream = require('stream')
6
7
var IncomingMessage = response.IncomingMessage
8
var rStates = response.readyStates
9
10
function decideMode (preferBinary) {
11
if (capability.fetch) {
12
return 'fetch'
13
} else if (capability.mozchunkedarraybuffer) {
14
return 'moz-chunked-arraybuffer'
15
} else if (capability.msstream) {
16
return 'ms-stream'
17
} else if (capability.arraybuffer && preferBinary) {
18
return 'arraybuffer'
19
} else if (capability.vbArray && preferBinary) {
20
return 'text:vbarray'
21
} else {
22
return 'text'
23
}
24
}
25
26
var ClientRequest = module.exports = function (opts) {
27
var self = this
28
stream.Writable.call(self)
29
30
self._opts = opts
31
self._body = []
32
self._headers = {}
33
if (opts.auth)
34
self.setHeader('Authorization', 'Basic ' + new Buffer(opts.auth).toString('base64'))
35
Object.keys(opts.headers).forEach(function (name) {
36
self.setHeader(name, opts.headers[name])
37
})
38
39
var preferBinary
40
if (opts.mode === 'prefer-streaming') {
41
// If streaming is a high priority but binary compatibility and
42
// the accuracy of the 'content-type' header aren't
43
preferBinary = false
44
} else if (opts.mode === 'allow-wrong-content-type') {
45
// If streaming is more important than preserving the 'content-type' header
46
preferBinary = !capability.overrideMimeType
47
} else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') {
48
// Use binary if text streaming may corrupt data or the content-type header, or for speed
49
preferBinary = true
50
} else {
51
throw new Error('Invalid value for opts.mode')
52
}
53
self._mode = decideMode(preferBinary)
54
55
self.on('finish', function () {
56
self._onFinish()
57
})
58
}
59
60
inherits(ClientRequest, stream.Writable)
61
62
ClientRequest.prototype.setHeader = function (name, value) {
63
var self = this
64
var lowerName = name.toLowerCase()
65
// This check is not necessary, but it prevents warnings from browsers about setting unsafe
66
// headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but
67
// http-browserify did it, so I will too.
68
if (unsafeHeaders.indexOf(lowerName) !== -1)
69
return
70
71
self._headers[lowerName] = {
72
name: name,
73
value: value
74
}
75
}
76
77
ClientRequest.prototype.getHeader = function (name) {
78
var self = this
79
return self._headers[name.toLowerCase()].value
80
}
81
82
ClientRequest.prototype.removeHeader = function (name) {
83
var self = this
84
delete self._headers[name.toLowerCase()]
85
}
86
87
ClientRequest.prototype._onFinish = function () {
88
var self = this
89
90
if (self._destroyed)
91
return
92
var opts = self._opts
93
94
var headersObj = self._headers
95
var body
96
if (opts.method === 'POST' || opts.method === 'PUT' || opts.method === 'PATCH') {
97
if (capability.blobConstructor) {
98
body = new global.Blob(self._body.map(function (buffer) {
99
if (buffer instanceof Uint8Array) {
100
return buffer
101
} else {
102
var buf = new Uint8Array(buffer.length)
103
for (var i = 0, len = buf.length; i < len; i++) {
104
buf[i] = buffer[i]
105
}
106
return buf
107
}
108
}), {
109
type: (headersObj['content-type'] || {}).value || ''
110
})
111
} else {
112
// get utf8 string
113
body = Buffer.concat(self._body).toString()
114
}
115
}
116
117
if (self._mode === 'fetch') {
118
var headers = Object.keys(headersObj).map(function (name) {
119
return [headersObj[name].name, headersObj[name].value]
120
})
121
122
global.fetch(self._opts.url, {
123
method: self._opts.method,
124
headers: headers,
125
body: body,
126
mode: 'cors',
127
credentials: opts.withCredentials ? 'include' : 'same-origin'
128
}).then(function (response) {
129
self._fetchResponse = response
130
self._connect()
131
}, function (reason) {
132
self.emit('error', reason)
133
})
134
} else {
135
var xhr = self._xhr = new global.XMLHttpRequest()
136
try {
137
xhr.open(self._opts.method, self._opts.url, true)
138
} catch (err) {
139
process.nextTick(function () {
140
self.emit('error', err)
141
})
142
return
143
}
144
145
// Can't set responseType on really old browsers
146
if ('responseType' in xhr)
147
xhr.responseType = self._mode.split(':')[0]
148
149
if ('withCredentials' in xhr)
150
xhr.withCredentials = !!opts.withCredentials
151
152
if (self._mode === 'text' && 'overrideMimeType' in xhr)
153
xhr.overrideMimeType('text/plain; charset=x-user-defined')
154
155
Object.keys(headersObj).forEach(function (name) {
156
xhr.setRequestHeader(headersObj[name].name, headersObj[name].value)
157
})
158
159
self._response = null
160
xhr.onreadystatechange = function () {
161
switch (xhr.readyState) {
162
case rStates.LOADING:
163
case rStates.DONE:
164
self._onXHRProgress()
165
break
166
}
167
}
168
// Necessary for streaming in Firefox, since xhr.response is ONLY defined
169
// in onprogress, not in onreadystatechange with xhr.readyState = 3
170
if (self._mode === 'moz-chunked-arraybuffer') {
171
xhr.onprogress = function () {
172
self._onXHRProgress()
173
}
174
}
175
176
xhr.onerror = function () {
177
if (self._destroyed)
178
return
179
self.emit('error', new Error('XHR error'))
180
}
181
182
try {
183
xhr.send(body)
184
} catch (err) {
185
process.nextTick(function () {
186
self.emit('error', err)
187
})
188
return
189
}
190
}
191
}
192
193
/**
194
* Checks if xhr.status is readable and non-zero, indicating no error.
195
* Even though the spec says it should be available in readyState 3,
196
* accessing it throws an exception in IE8
197
*/
198
function statusValid (xhr) {
199
try {
200
var status = xhr.status
201
return (status !== null && status !== 0)
202
} catch (e) {
203
return false
204
}
205
}
206
207
ClientRequest.prototype._onXHRProgress = function () {
208
var self = this
209
210
if (!statusValid(self._xhr) || self._destroyed)
211
return
212
213
if (!self._response)
214
self._connect()
215
216
self._response._onXHRProgress()
217
}
218
219
ClientRequest.prototype._connect = function () {
220
var self = this
221
222
if (self._destroyed)
223
return
224
225
self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode)
226
self.emit('response', self._response)
227
}
228
229
ClientRequest.prototype._write = function (chunk, encoding, cb) {
230
var self = this
231
232
self._body.push(chunk)
233
cb()
234
}
235
236
ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () {
237
var self = this
238
self._destroyed = true
239
if (self._response)
240
self._response._destroyed = true
241
if (self._xhr)
242
self._xhr.abort()
243
// Currently, there isn't a way to truly abort a fetch.
244
// If you like bikeshedding, see https://github.com/whatwg/fetch/issues/27
245
}
246
247
ClientRequest.prototype.end = function (data, encoding, cb) {
248
var self = this
249
if (typeof data === 'function') {
250
cb = data
251
data = undefined
252
}
253
254
stream.Writable.prototype.end.call(self, data, encoding, cb)
255
}
256
257
ClientRequest.prototype.flushHeaders = function () {}
258
ClientRequest.prototype.setTimeout = function () {}
259
ClientRequest.prototype.setNoDelay = function () {}
260
ClientRequest.prototype.setSocketKeepAlive = function () {}
261
262
// Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method
263
var unsafeHeaders = [
264
'accept-charset',
265
'accept-encoding',
266
'access-control-request-headers',
267
'access-control-request-method',
268
'connection',
269
'content-length',
270
'cookie',
271
'cookie2',
272
'date',
273
'dnt',
274
'expect',
275
'host',
276
'keep-alive',
277
'origin',
278
'referer',
279
'te',
280
'trailer',
281
'transfer-encoding',
282
'upgrade',
283
'user-agent',
284
'via'
285
]