forked from node-fetch/node-fetch
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
240 lines (196 loc) · 8.2 KB
/
index.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
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
'use strict';
/**
* index.js
*
* a request API compatible with window.fetch
*/
const parse_url = require('url').parse;
const resolve_url = require('url').resolve;
const http = require('http');
const https = require('https');
const zlib = require('zlib');
const stream = require('stream');
const Body = require('./lib/body');
const Response = require('./lib/response');
const Headers = require('./lib/headers');
const Request = require('./lib/request');
const FetchError = require('./lib/fetch-error');
const webStreams = require('node-web-streams');
/**
* Fetch class
*
* @param Mixed url Absolute url or Request instance
* @param Object opts Fetch options
* @return Promise
*/
function fetch(url, opts) {
// allow custom promise
if (!fetch.Promise) {
throw new Error('native promise missing, set Fetch.Promise to your favorite alternative');
}
Body.Promise = fetch.Promise;
// wrap http.request into fetch
return new fetch.Promise((resolve, reject) => {
// build request object
const request = new Request(url, opts);
if (!request.protocol || !request.hostname) {
throw new Error('only absolute urls are supported');
}
if (request.protocol !== 'http:' && request.protocol !== 'https:') {
throw new Error('only http(s) protocols are supported');
}
let send;
if (request.protocol === 'https:') {
send = https.request;
} else {
send = http.request;
}
// normalize headers
const headers = new Headers(request.headers);
if (request.compress) {
headers.set('accept-encoding', 'gzip,deflate');
}
if (!headers.has('user-agent')) {
headers.set('user-agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)');
}
if (!headers.has('connection') && !request.agent) {
headers.set('connection', 'close');
}
if (!headers.has('accept')) {
headers.set('accept', '*/*');
}
// detect form data input from form-data module, this hack avoid the need to pass multipart header manually
if (!headers.has('content-type') && request._rawBody
&& typeof request._rawBody.getBoundary === 'function') {
headers.set('content-type', `multipart/form-data; boundary=${request.body.getBoundary()}`);
}
// bring node-fetch closer to browser behavior by setting content-length automatically
if (!headers.has('content-length') && /post|put|patch|delete/i.test(request.method)) {
if (typeof request._rawBody === 'string') {
request._rawBody = new Buffer(request._rawBody);
}
if (Buffer.isBuffer(request._rawBody)) {
headers.set('content-length', request._rawBody.length);
// detect form data input from form-data module, this hack avoid the need to add content-length header manually
} else if (request._rawBody
&& typeof request._rawBody.getLengthSync === 'function'
&& request._rawBody._lengthRetrievers.length === 0) {
headers.set('content-length', request._rawBody.getLengthSync().toString());
// this is only necessary for older nodejs releases (before iojs merge)
} else if (request._rawBody === undefined || request._rawBody === null) {
headers.set('content-length', '0');
}
}
request.headers = headers.raw();
// http.request only support string as host header, this hack make custom host header possible
if (request.headers.host) {
request.headers.host = request.headers.host[0];
}
// send request
const req = send(request);
let reqTimeout;
if (request.timeout) {
req.once('socket', socket => {
reqTimeout = setTimeout(() => {
req.abort();
reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout'));
}, request.timeout);
});
}
req.on('error', err => {
clearTimeout(reqTimeout);
reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
});
req.on('response', res => {
clearTimeout(reqTimeout);
// handle redirect
if (fetch.isRedirect(res.statusCode) && request.redirect !== 'manual') {
if (request.redirect === 'error') {
reject(new FetchError(`redirect mode is set to error: ${request.url}`, 'no-redirect'));
return;
}
if (request.counter >= request.follow) {
reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect'));
return;
}
if (!res.headers.location) {
reject(new FetchError(`redirect location header missing at: ${request.url}`, 'invalid-redirect'));
return;
}
// per fetch spec, for POST request with 301/302 response, or any request with 303 response, use GET when following redirect
if (res.statusCode === 303
|| ((res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST'))
{
request.method = 'GET';
request.body = undefined;
delete request.headers['content-length'];
}
request.counter++;
resolve(fetch(resolve_url(request.url, res.headers.location), request));
return;
}
// handle compression
let body = res;
const headers = new Headers(res.headers);
if (request.compress && headers.has('content-encoding')) {
const name = headers.get('content-encoding');
// no need to pipe no content and not modified response body
if (res.statusCode !== 204 && res.statusCode !== 304) {
if (name === 'gzip' || name === 'x-gzip') {
body = body.pipe(zlib.createGunzip());
} else if (name === 'deflate' || name === 'x-deflate') {
body = body.pipe(zlib.createInflate());
}
}
}
// normalize location header for manual redirect mode
if (request.redirect === 'manual' && headers.has('location')) {
headers.set('location', resolve_url(request.url, headers.get('location')));
}
// response object
const output = new Response(body, {
url: request.url,
status: res.statusCode,
statusText: res.statusMessage,
headers: headers,
size: request.size,
timeout: request.timeout
});
resolve(output);
});
// Request body handling
if (request._rawBody !== undefined && request._rawBody !== null) {
if (Buffer.isBuffer(request._rawBody)) {
// Fast path for simple buffers. Avoid stream wrapper &
// chunked encoding.
return req.end(request._rawBody);
} else if (request._rawBody.pipe) {
// Node stream (likely FormData).
return request._rawBody.pipe(req);
} else {
// Standard ReadableStream
const nodeBody = webStreams.toNodeReadable(request.body);
return nodeBody.pipe(req);
}
}
req.end();
});
}
/**
* Redirect code matching
*
* @param Number code Status code
* @return Boolean
*/
fetch.isRedirect = function isRedirect(code) {
return code === 301 || code === 302 || code === 303 || code === 307 || code === 308;
};
// expose Promise
fetch.Promise = global.Promise;
fetch.Response = Response;
fetch.Headers = Headers;
fetch.Request = Request;
// commonjs
module.exports = fetch;
// es6 default export compatibility
module.exports.default = module.exports;