1 | <div align="center">
|
2 | <br>
|
3 | <br>
|
4 | <img width="360" src="media/logo.svg" alt="Got">
|
5 | <br>
|
6 | <br>
|
7 | <br>
|
8 | <p align="center">Huge thanks to <a href="https://moxy.studio"><img src="https://sindresorhus.com/assets/thanks/moxy-logo.svg" width="150"></a> for sponsoring me!
|
9 | </p>
|
10 | <br>
|
11 | <br>
|
12 | </div>
|
13 |
|
14 | > Simplified HTTP requests
|
15 |
|
16 | [![Build Status: Linux](https://travis-ci.org/sindresorhus/got.svg?branch=master)](https://travis-ci.org/sindresorhus/got) [![Coverage Status](https://coveralls.io/repos/github/sindresorhus/got/badge.svg?branch=master)](https://coveralls.io/github/sindresorhus/got?branch=master) [![Downloads](https://img.shields.io/npm/dm/got.svg)](https://npmjs.com/got) [![Install size](https://packagephobia.now.sh/badge?p=got)](https://packagephobia.now.sh/result?p=got)
|
17 |
|
18 | Got is a human-friendly and powerful HTTP request library.
|
19 |
|
20 | It was created because the popular [`request`](https://github.com/request/request) package is bloated: [![Install size](https://packagephobia.now.sh/badge?p=request)](https://packagephobia.now.sh/result?p=request)
|
21 |
|
22 |
|
23 | ## Highlights
|
24 |
|
25 | - [Promise & stream API](#api)
|
26 | - [Request cancelation](#aborting-the-request)
|
27 | - [RFC compliant caching](#cache-adapters)
|
28 | - [Follows redirects](#followredirect)
|
29 | - [Retries on failure](#retry)
|
30 | - [Progress events](#onuploadprogress-progress)
|
31 | - [Handles gzip/deflate](#decompress)
|
32 | - [Timeout handling](#timeout)
|
33 | - [Errors with metadata](#errors)
|
34 | - [JSON mode](#json)
|
35 | - [WHATWG URL support](#url)
|
36 | - [Electron support](#useelectronnet)
|
37 | - [Instances with custom defaults](#instances)
|
38 | - [Composable](advanced-creation.md#merging-instances)
|
39 | - [Used by ~2000 packages and ~500K repos](https://github.com/sindresorhus/got/network/dependents)
|
40 | - Actively maintained
|
41 |
|
42 | [See how Got compares to other HTTP libraries](#comparison)
|
43 |
|
44 |
|
45 | ## Install
|
46 |
|
47 | ```
|
48 | $ npm install got
|
49 | ```
|
50 |
|
51 | <a href="https://www.patreon.com/sindresorhus">
|
52 | <img src="https://c5.patreon.com/external/logo/become_a_patron_button@2x.png" width="160">
|
53 | </a>
|
54 |
|
55 |
|
56 | ## Usage
|
57 |
|
58 | ```js
|
59 | const got = require('got');
|
60 |
|
61 | (async () => {
|
62 | try {
|
63 | const response = await got('sindresorhus.com');
|
64 | console.log(response.body);
|
65 | //=> '<!doctype html> ...'
|
66 | } catch (error) {
|
67 | console.log(error.response.body);
|
68 | //=> 'Internal server error ...'
|
69 | }
|
70 | })();
|
71 | ```
|
72 |
|
73 | ###### Streams
|
74 |
|
75 | ```js
|
76 | const fs = require('fs');
|
77 | const got = require('got');
|
78 |
|
79 | got.stream('sindresorhus.com').pipe(fs.createWriteStream('index.html'));
|
80 |
|
81 | // For POST, PUT, and PATCH methods `got.stream` returns a `stream.Writable`
|
82 | fs.createReadStream('index.html').pipe(got.stream.post('sindresorhus.com'));
|
83 | ```
|
84 |
|
85 |
|
86 | ### API
|
87 |
|
88 | It's a `GET` request by default, but can be changed by using different methods or in the `options`.
|
89 |
|
90 | #### got(url, [options])
|
91 |
|
92 | Returns a Promise for a `response` object with a `body` property, a `url` property with the request URL or the final URL after redirects, and a `requestUrl` property with the original request URL.
|
93 |
|
94 | The response object will typically be a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage), however, if returned from the cache it will be a [response-like object](https://github.com/lukechilds/responselike) which behaves in the same way.
|
95 |
|
96 | The response will also have a `fromCache` property set with a boolean value.
|
97 |
|
98 | ##### url
|
99 |
|
100 | Type: `string` `Object`
|
101 |
|
102 | The URL to request, as a string, a [`https.request` options object](https://nodejs.org/api/https.html#https_https_request_options_callback), or a [WHATWG `URL`](https://nodejs.org/api/url.html#url_class_url).
|
103 |
|
104 | Properties from `options` will override properties in the parsed `url`.
|
105 |
|
106 | If no protocol is specified, it will default to `https`.
|
107 |
|
108 | ##### options
|
109 |
|
110 | Type: `Object`
|
111 |
|
112 | Any of the [`https.request`](https://nodejs.org/api/https.html#https_https_request_options_callback) options.
|
113 |
|
114 | ###### baseUrl
|
115 |
|
116 | Type: `string` `Object`
|
117 |
|
118 | When specified, `url` will be prepended by `baseUrl`.<br>
|
119 | If you specify an absolute URL, it will skip the `baseUrl`.
|
120 |
|
121 | Very useful when used with `got.extend()` to create niche-specific Got instances.
|
122 |
|
123 | Can be a string or a [WHATWG `URL`](https://nodejs.org/api/url.html#url_class_url).
|
124 |
|
125 | Backslash at the end of `baseUrl` and at the beginning of the `url` argument is optional:
|
126 |
|
127 | ```js
|
128 | await got('hello', {baseUrl: 'https://example.com/v1'});
|
129 | //=> 'https://example.com/v1/hello'
|
130 |
|
131 | await got('/hello', {baseUrl: 'https://example.com/v1/'});
|
132 | //=> 'https://example.com/v1/hello'
|
133 |
|
134 | await got('/hello', {baseUrl: 'https://example.com/v1'});
|
135 | //=> 'https://example.com/v1/hello'
|
136 | ```
|
137 |
|
138 | ###### headers
|
139 |
|
140 | Type: `Object`<br>
|
141 | Default: `{}`
|
142 |
|
143 | Request headers.
|
144 |
|
145 | Existing headers will be overwritten. Headers set to `null` will be omitted.
|
146 |
|
147 | ###### stream
|
148 |
|
149 | Type: `boolean`<br>
|
150 | Default: `false`
|
151 |
|
152 | Returns a `Stream` instead of a `Promise`. This is equivalent to calling `got.stream(url, [options])`.
|
153 |
|
154 | ###### body
|
155 |
|
156 | Type: `string` `Buffer` `stream.Readable` [`form-data` instance](https://github.com/form-data/form-data)
|
157 |
|
158 | *If you provide this option, `got.stream()` will be read-only.*
|
159 |
|
160 | The body that will be sent with a `POST` request.
|
161 |
|
162 | If present in `options` and `options.method` is not set, `options.method` will be set to `POST`.
|
163 |
|
164 | The `content-length` header will be automatically set if `body` is a `string` / `Buffer` / `fs.createReadStream` instance / [`form-data` instance](https://github.com/form-data/form-data), and `content-length` and `transfer-encoding` are not manually set in `options.headers`.
|
165 |
|
166 | ###### encoding
|
167 |
|
168 | Type: `string` `null`<br>
|
169 | Default: `'utf8'`
|
170 |
|
171 | [Encoding](https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings) to be used on `setEncoding` of the response data. If `null`, the body is returned as a [`Buffer`](https://nodejs.org/api/buffer.html) (binary data).
|
172 |
|
173 | ###### form
|
174 |
|
175 | Type: `boolean`<br>
|
176 | Default: `false`
|
177 |
|
178 | *If you provide this option, `got.stream()` will be read-only.*
|
179 |
|
180 | If set to `true` and `Content-Type` header is not set, it will be set to `application/x-www-form-urlencoded`.
|
181 |
|
182 | `body` must be a plain object. It will be converted to a query string using [`(new URLSearchParams(object)).toString()`](https://nodejs.org/api/url.html#url_constructor_new_urlsearchparams_obj).
|
183 |
|
184 | ###### json
|
185 |
|
186 | Type: `boolean`<br>
|
187 | Default: `false`
|
188 |
|
189 | *If you use `got.stream()`, this option will be ignored.*
|
190 |
|
191 | If set to `true` and `Content-Type` header is not set, it will be set to `application/json`.
|
192 |
|
193 | Parse response body with `JSON.parse` and set `accept` header to `application/json`. If used in conjunction with the `form` option, the `body` will the stringified as querystring and the response parsed as JSON.
|
194 |
|
195 | `body` must be a plain object or array and will be stringified.
|
196 |
|
197 | ###### query
|
198 |
|
199 | Type: `string` `Object` [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
|
200 |
|
201 | Query string object that will be added to the request URL. This will override the query string in `url`.
|
202 |
|
203 | ###### timeout
|
204 |
|
205 | Type: `number` `Object`
|
206 |
|
207 | Milliseconds to wait for the server to end the response before aborting the request with [`got.TimeoutError`](#gottimeouterror) error (a.k.a. `request` property). By default, there's no timeout.
|
208 |
|
209 | This also accepts an `object` with the following fields to constrain the duration of each phase of the request lifecycle:
|
210 |
|
211 | - `lookup` starts when a socket is assigned and ends when the hostname has been resolved. Does not apply when using a Unix domain socket.
|
212 | - `connect` starts when `lookup` completes (or when the socket is assigned if lookup does not apply to the request) and ends when the socket is connected.
|
213 | - `secureConnect` starts when `connect` completes and ends when the handshaking process completes (HTTPS only).
|
214 | - `socket` starts when the socket is connected. See [request.setTimeout](https://nodejs.org/api/http.html#http_request_settimeout_timeout_callback).
|
215 | - `response` starts when the request has been written to the socket and ends when the response headers are received.
|
216 | - `send` starts when the socket is connected and ends with the request has been written to the socket.
|
217 | - `request` starts when the request is initiated and ends when the response's end event fires.
|
218 |
|
219 | ###### retry
|
220 |
|
221 | Type: `number` `Object`<br>
|
222 | Default:
|
223 | - retries: `2`
|
224 | - methods: `GET` `PUT` `HEAD` `DELETE` `OPTIONS` `TRACE`
|
225 | - statusCodes: [`408`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/408) [`413`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/413) [`429`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429) [`500`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500) [`502`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/502) [`503`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/503) [`504`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504)
|
226 | - maxRetryAfter: `undefined`
|
227 |
|
228 | An object representing `retries`, `methods`, `statusCodes` and `maxRetryAfter` fields for the time until retry, allowed methods, allowed status codes and maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time.
|
229 |
|
230 | If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`.<br>
|
231 | If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will cancel the request.
|
232 |
|
233 | Delays between retries counts with function `1000 * Math.pow(2, retry) + Math.random() * 100`, where `retry` is attempt number (starts from 0).
|
234 |
|
235 | The `retries` property can be a `number` or a `function` with `retry` and `error` arguments. The function must return a delay in milliseconds (`0` return value cancels retry).
|
236 |
|
237 | **Note:** It retries only on the specified methods, status codes, and on these network errors:
|
238 | - `ETIMEDOUT`: One of the [timeout](#timeout) limits were reached.
|
239 | - `ECONNRESET`: Connection was forcibly closed by a peer.
|
240 | - `EADDRINUSE`: Could not bind to any free port.
|
241 | - `ECONNREFUSED`: Connection was refused by the server.
|
242 | - `EPIPE`: The remote side of the stream being written has been closed.
|
243 |
|
244 | ###### followRedirect
|
245 |
|
246 | Type: `boolean`<br>
|
247 | Default: `true`
|
248 |
|
249 | Defines if redirect responses should be followed automatically.
|
250 |
|
251 | Note that if a `303` is sent by the server in response to any request type (`POST`, `DELETE`, etc.), Got will automatically request the resource pointed to in the location header via `GET`. This is in accordance with [the spec](https://tools.ietf.org/html/rfc7231#section-6.4.4).
|
252 |
|
253 | ###### decompress
|
254 |
|
255 | Type: `boolean`<br>
|
256 | Default: `true`
|
257 |
|
258 | Decompress the response automatically. This will set the `accept-encoding` header to `gzip, deflate` unless you set it yourself.
|
259 |
|
260 | If this is disabled, a compressed response is returned as a `Buffer`. This may be useful if you want to handle decompression yourself or stream the raw compressed data.
|
261 |
|
262 | ###### cache
|
263 |
|
264 | Type: `Object`<br>
|
265 | Default: `false`
|
266 |
|
267 | [Cache adapter instance](#cache-adapters) for storing cached data.
|
268 |
|
269 | ###### useElectronNet
|
270 |
|
271 | Type: `boolean`<br>
|
272 | Default: `false`
|
273 |
|
274 | When used in Electron, Got will use [`electron.net`](https://electronjs.org/docs/api/net/) instead of the Node.js `http` module. According to the Electron docs, it should be fully compatible, but it's not entirely. See [#443](https://github.com/sindresorhus/got/issues/443) and [#461](https://github.com/sindresorhus/got/issues/461).
|
275 |
|
276 | ###### throwHttpErrors
|
277 |
|
278 | Type: `boolean`<br>
|
279 | Default: `true`
|
280 |
|
281 | Determines if a `got.HTTPError` is thrown for error responses (non-2xx status codes).
|
282 |
|
283 | If this is disabled, requests that encounter an error status code will be resolved with the `response` instead of throwing. This may be useful if you are checking for resource availability and are expecting error responses.
|
284 |
|
285 | ###### hooks
|
286 |
|
287 | Type: `Object<string, Function[]>`<br>
|
288 | Default: `{beforeRequest: []}`
|
289 |
|
290 | Hooks allow modifications during the request lifecycle. Hook functions may be async and are run serially.
|
291 |
|
292 | ###### hooks.beforeRequest
|
293 |
|
294 | Type: `Function[]`<br>
|
295 | Default: `[]`
|
296 |
|
297 | Called with the normalized request options. Got will make no further changes to the request before it is sent. This is especially useful in conjunction with [`got.extend()`](#instances) and [`got.create()`](advanced-creation.md) when you want to create an API client that, for example, uses HMAC-signing.
|
298 |
|
299 | See the [AWS section](#aws) for an example.
|
300 |
|
301 | **Note**: Modifying the `body` is not recommended because the `content-length` header has already been computed and assigned.
|
302 |
|
303 | #### Streams
|
304 |
|
305 | **Note**: Progress events, redirect events and request/response events can also be used with promises.
|
306 |
|
307 | #### got.stream(url, [options])
|
308 |
|
309 | Sets `options.stream` to `true`.
|
310 |
|
311 | Returna a [duplex stream](https://nodejs.org/api/stream.html#stream_class_stream_duplex) with additional events:
|
312 |
|
313 | ##### .on('request', request)
|
314 |
|
315 | `request` event to get the request object of the request.
|
316 |
|
317 | **Tip**: You can use `request` event to abort request:
|
318 |
|
319 | ```js
|
320 | got.stream('github.com')
|
321 | .on('request', request => setTimeout(() => request.abort(), 50));
|
322 | ```
|
323 |
|
324 | ##### .on('response', response)
|
325 |
|
326 | The `response` event to get the response object of the final request.
|
327 |
|
328 | ##### .on('redirect', response, nextOptions)
|
329 |
|
330 | The `redirect` event to get the response object of a redirect. The second argument is options for the next request to the redirect location.
|
331 |
|
332 | ##### .on('uploadProgress', progress)
|
333 | ##### .on('downloadProgress', progress)
|
334 |
|
335 | Progress events for uploading (sending a request) and downloading (receiving a response). The `progress` argument is an object like:
|
336 |
|
337 | ```js
|
338 | {
|
339 | percent: 0.1,
|
340 | transferred: 1024,
|
341 | total: 10240
|
342 | }
|
343 | ```
|
344 |
|
345 | If it's not possible to retrieve the body size (can happen when streaming), `total` will be `null`.
|
346 |
|
347 | ```js
|
348 | (async () => {
|
349 | const response = await got('sindresorhus.com')
|
350 | .on('downloadProgress', progress => {
|
351 | // Report download progress
|
352 | })
|
353 | .on('uploadProgress', progress => {
|
354 | // Report upload progress
|
355 | });
|
356 |
|
357 | console.log(response);
|
358 | })();
|
359 | ```
|
360 |
|
361 | ##### .on('error', error, body, response)
|
362 |
|
363 | The `error` event emitted in case of a protocol error (like `ENOTFOUND` etc.) or status error (4xx or 5xx). The second argument is the body of the server response in case of status error. The third argument is a response object.
|
364 |
|
365 | #### got.get(url, [options])
|
366 | #### got.post(url, [options])
|
367 | #### got.put(url, [options])
|
368 | #### got.patch(url, [options])
|
369 | #### got.head(url, [options])
|
370 | #### got.delete(url, [options])
|
371 |
|
372 | Sets `options.method` to the method name and makes a request.
|
373 |
|
374 | ### Instances
|
375 |
|
376 | #### got.extend([options])
|
377 |
|
378 | Configure a new `got` instance with default `options`. `options` are merged with the parent instance's `defaults.options` using [`got.mergeOptions`](#gotmergeoptionsparentoptions-newoptions).
|
379 |
|
380 | ```js
|
381 | const client = got.extend({
|
382 | baseUrl: 'https://example.com',
|
383 | headers: {
|
384 | 'x-unicorn': 'rainbow'
|
385 | }
|
386 | });
|
387 |
|
388 | client.get('/demo');
|
389 |
|
390 | /* HTTP Request =>
|
391 | * GET /demo HTTP/1.1
|
392 | * Host: example.com
|
393 | * x-unicorn: rainbow
|
394 | */
|
395 | ```
|
396 |
|
397 | ```js
|
398 | (async () => {
|
399 | const client = got.extend({
|
400 | baseUrl: 'httpbin.org',
|
401 | headers: {
|
402 | 'x-foo': 'bar'
|
403 | }
|
404 | });
|
405 | const {headers} = (await client.get('/headers', {json: true})).body;
|
406 | //=> headers['x-foo'] === 'bar'
|
407 |
|
408 | const jsonClient = client.extend({
|
409 | json: true,
|
410 | headers: {
|
411 | 'x-baz': 'qux'
|
412 | }
|
413 | });
|
414 | const {headers: headers2} = (await jsonClient.get('/headers')).body;
|
415 | //=> headers2['x-foo'] === 'bar'
|
416 | //=> headers2['x-baz'] === 'qux'
|
417 | })();
|
418 | ```
|
419 |
|
420 | *Need more control over the behavior of Got? Check out the [`got.create()`](advanced-creation.md).*
|
421 |
|
422 | #### got.mergeOptions(parentOptions, newOptions)
|
423 |
|
424 | Extends parent options. Avoid using [object spread](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#Spread_in_object_literals) as it doesn't work recursively:
|
425 |
|
426 | ```js
|
427 | const a = {headers: {cat: 'meow', wolf: ['bark', 'wrrr']}};
|
428 | const b = {headers: {cow: 'moo', wolf: ['auuu']}};
|
429 |
|
430 | {...a, ...b} // => {headers: {cow: 'moo', wolf: ['auuu']}}
|
431 | got.mergeOptions(a, b) // => {headers: {cat: 'meow', cow: 'moo', wolf: ['auuu']}}
|
432 | ```
|
433 |
|
434 | Options are deeply merged to a new object. The value of each key is determined as follows:
|
435 |
|
436 | - If the new property is set to `undefined`, it keeps the old one.
|
437 | - If the parent property is an instance of `URL` and the new value is a `string` or `URL`, a new URL instance is created: [`new URL(new, parent)`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL#Syntax).
|
438 | - If the new property is a plain `Object`:
|
439 | - If the parent property is a plain `Object` too, both values are merged recursively into a new `Object`.
|
440 | - Otherwise, only the new value is deeply cloned.
|
441 | - If the new property is an `Array`, it overwrites the old one with a deep clone of the new property.
|
442 | - Otherwise, the new value is assigned to the key.
|
443 |
|
444 | ## Errors
|
445 |
|
446 | Each error contains (if available) `statusCode`, `statusMessage`, `host`, `hostname`, `method`, `path`, `protocol` and `url` properties to make debugging easier.
|
447 |
|
448 | In Promise mode, the `response` is attached to the error.
|
449 |
|
450 | #### got.CacheError
|
451 |
|
452 | When a cache method fails, for example, if the database goes down or there's a filesystem error.
|
453 |
|
454 | #### got.RequestError
|
455 |
|
456 | When a request fails. Contains a `code` property with error class code, like `ECONNREFUSED`.
|
457 |
|
458 | #### got.ReadError
|
459 |
|
460 | When reading from response stream fails.
|
461 |
|
462 | #### got.ParseError
|
463 |
|
464 | When `json` option is enabled, server response code is 2xx, and `JSON.parse` fails.
|
465 |
|
466 | #### got.HTTPError
|
467 |
|
468 | When the server response code is not 2xx. Includes `statusCode`, `statusMessage`, and `redirectUrls` properties.
|
469 |
|
470 | #### got.MaxRedirectsError
|
471 |
|
472 | When the server redirects you more than ten times. Includes a `redirectUrls` property, which is an array of the URLs Got was redirected to before giving up.
|
473 |
|
474 | #### got.UnsupportedProtocolError
|
475 |
|
476 | When given an unsupported protocol.
|
477 |
|
478 | #### got.CancelError
|
479 |
|
480 | When the request is aborted with `.cancel()`.
|
481 |
|
482 | #### got.TimeoutError
|
483 |
|
484 | When the request is aborted due to a [timeout](#timeout)
|
485 |
|
486 | ## Aborting the request
|
487 |
|
488 | The promise returned by Got has a [`.cancel()`](https://github.com/sindresorhus/p-cancelable) method which when called, aborts the request.
|
489 |
|
490 | ```js
|
491 | (async () => {
|
492 | const request = got(url, options);
|
493 |
|
494 | // …
|
495 |
|
496 | // In another part of the code
|
497 | if (something) {
|
498 | request.cancel();
|
499 | }
|
500 |
|
501 | // …
|
502 |
|
503 | try {
|
504 | await request;
|
505 | } catch (error) {
|
506 | if (request.isCanceled) { // Or `error instanceof got.CancelError`
|
507 | // Handle cancelation
|
508 | }
|
509 |
|
510 | // Handle other errors
|
511 | }
|
512 | })();
|
513 | ```
|
514 |
|
515 | <a name="cache-adapters"></a>
|
516 | ## Cache
|
517 |
|
518 | Got implements [RFC 7234](http://httpwg.org/specs/rfc7234.html) compliant HTTP caching which works out of the box in-memory and is easily pluggable with a wide range of storage adapters. Fresh cache entries are served directly from the cache, and stale cache entries are revalidated with `If-None-Match`/`If-Modified-Since` headers. You can read more about the underlying cache behavior in the [`cacheable-request` documentation](https://github.com/lukechilds/cacheable-request).
|
519 |
|
520 | You can use the JavaScript `Map` type as an in-memory cache:
|
521 |
|
522 | ```js
|
523 | const got = require('got');
|
524 | const map = new Map();
|
525 |
|
526 | (async () => {
|
527 | let response = await got('sindresorhus.com', {cache: map});
|
528 | console.log(response.fromCache);
|
529 | //=> false
|
530 |
|
531 | response = await got('sindresorhus.com', {cache: map});
|
532 | console.log(response.fromCache);
|
533 | //=> true
|
534 | })();
|
535 | ```
|
536 |
|
537 | Got uses [Keyv](https://github.com/lukechilds/keyv) internally to support a wide range of storage adapters. For something more scalable you could use an [official Keyv storage adapter](https://github.com/lukechilds/keyv#official-storage-adapters):
|
538 |
|
539 | ```
|
540 | $ npm install @keyv/redis
|
541 | ```
|
542 |
|
543 | ```js
|
544 | const got = require('got');
|
545 | const KeyvRedis = require('@keyv/redis');
|
546 |
|
547 | const redis = new KeyvRedis('redis://user:pass@localhost:6379');
|
548 |
|
549 | got('sindresorhus.com', {cache: redis});
|
550 | ```
|
551 |
|
552 | Got supports anything that follows the Map API, so it's easy to write your own storage adapter or use a third-party solution.
|
553 |
|
554 | For example, the following are all valid storage adapters:
|
555 |
|
556 | ```js
|
557 | const storageAdapter = new Map();
|
558 | // Or
|
559 | const storageAdapter = require('./my-storage-adapter');
|
560 | // Or
|
561 | const QuickLRU = require('quick-lru');
|
562 | const storageAdapter = new QuickLRU({maxSize: 1000});
|
563 |
|
564 | got('sindresorhus.com', {cache: storageAdapter});
|
565 | ```
|
566 |
|
567 | View the [Keyv docs](https://github.com/lukechilds/keyv) for more information on how to use storage adapters.
|
568 |
|
569 |
|
570 | ## Proxies
|
571 |
|
572 | You can use the [`tunnel`](https://github.com/koichik/node-tunnel) module with the `agent` option to work with proxies:
|
573 |
|
574 | ```js
|
575 | const got = require('got');
|
576 | const tunnel = require('tunnel-agent');
|
577 |
|
578 | got('sindresorhus.com', {
|
579 | agent: tunnel.httpOverHttp({
|
580 | proxy: {
|
581 | host: 'localhost'
|
582 | }
|
583 | })
|
584 | });
|
585 | ```
|
586 |
|
587 | If you require different agents for different protocols, you can pass a map of agents to the `agent` option. This is necessary because a request to one protocol might redirect to another. In such a scenario, `got` will switch over to the right protocol agent for you.
|
588 |
|
589 | ```js
|
590 | const got = require('got');
|
591 | const HttpAgent = require('agentkeepalive');
|
592 | const HttpsAgent = HttpAgent.HttpsAgent;
|
593 |
|
594 | got('sindresorhus.com', {
|
595 | agent: {
|
596 | http: new HttpAgent(),
|
597 | https: new HttpsAgent()
|
598 | }
|
599 | });
|
600 | ```
|
601 |
|
602 | Check out [`global-tunnel`](https://github.com/np-maintain/global-tunnel) if you want to configure proxy support for all HTTP/HTTPS traffic in your app.
|
603 |
|
604 |
|
605 | ## Cookies
|
606 |
|
607 | You can use the [`cookie`](https://github.com/jshttp/cookie) module to include cookies in a request:
|
608 |
|
609 | ```js
|
610 | const got = require('got');
|
611 | const cookie = require('cookie');
|
612 |
|
613 | got('google.com', {
|
614 | headers: {
|
615 | cookie: cookie.serialize('foo', 'bar')
|
616 | }
|
617 | });
|
618 |
|
619 | got('google.com', {
|
620 | headers: {
|
621 | cookie: [
|
622 | cookie.serialize('foo', 'bar'),
|
623 | cookie.serialize('fizz', 'buzz')
|
624 | ].join(';')
|
625 | }
|
626 | });
|
627 | ```
|
628 |
|
629 |
|
630 | ## Form data
|
631 |
|
632 | You can use the [`form-data`](https://github.com/form-data/form-data) module to create POST request with form data:
|
633 |
|
634 | ```js
|
635 | const fs = require('fs');
|
636 | const got = require('got');
|
637 | const FormData = require('form-data');
|
638 | const form = new FormData();
|
639 |
|
640 | form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
|
641 |
|
642 | got.post('google.com', {
|
643 | body: form
|
644 | });
|
645 | ```
|
646 |
|
647 |
|
648 | ## OAuth
|
649 |
|
650 | You can use the [`oauth-1.0a`](https://github.com/ddo/oauth-1.0a) module to create a signed OAuth request:
|
651 |
|
652 | ```js
|
653 | const got = require('got');
|
654 | const crypto = require('crypto');
|
655 | const OAuth = require('oauth-1.0a');
|
656 |
|
657 | const oauth = OAuth({
|
658 | consumer: {
|
659 | key: process.env.CONSUMER_KEY,
|
660 | secret: process.env.CONSUMER_SECRET
|
661 | },
|
662 | signature_method: 'HMAC-SHA1',
|
663 | hash_function: (baseString, key) => crypto.createHmac('sha1', key).update(baseString).digest('base64')
|
664 | });
|
665 |
|
666 | const token = {
|
667 | key: process.env.ACCESS_TOKEN,
|
668 | secret: process.env.ACCESS_TOKEN_SECRET
|
669 | };
|
670 |
|
671 | const url = 'https://api.twitter.com/1.1/statuses/home_timeline.json';
|
672 |
|
673 | got(url, {
|
674 | headers: oauth.toHeader(oauth.authorize({url, method: 'GET'}, token)),
|
675 | json: true
|
676 | });
|
677 | ```
|
678 |
|
679 |
|
680 | ## Unix Domain Sockets
|
681 |
|
682 | Requests can also be sent via [unix domain sockets](http://serverfault.com/questions/124517/whats-the-difference-between-unix-socket-and-tcp-ip-socket). Use the following URL scheme: `PROTOCOL://unix:SOCKET:PATH`.
|
683 |
|
684 | - `PROTOCOL` - `http` or `https` *(optional)*
|
685 | - `SOCKET` - Absolute path to a unix domain socket, for example: `/var/run/docker.sock`
|
686 | - `PATH` - Request path, for example: `/v2/keys`
|
687 |
|
688 | ```js
|
689 | got('http://unix:/var/run/docker.sock:/containers/json');
|
690 |
|
691 | // Or without protocol (HTTP by default)
|
692 | got('unix:/var/run/docker.sock:/containers/json');
|
693 | ```
|
694 |
|
695 |
|
696 | ## AWS
|
697 |
|
698 | Requests to AWS services need to have their headers signed. This can be accomplished by using the [`aws4`](https://www.npmjs.com/package/aws4) package. This is an example for querying an ["API Gateway"](https://docs.aws.amazon.com/apigateway/api-reference/signing-requests/) with a signed request.
|
699 |
|
700 | ```js
|
701 | const AWS = require('aws-sdk');
|
702 | const aws4 = require('aws4');
|
703 | const got = require('got');
|
704 |
|
705 | const chain = new AWS.CredentialProviderChain();
|
706 |
|
707 | // Create a Got instance to use relative paths and signed requests
|
708 | const awsClient = got.extend({
|
709 | baseUrl: 'https://<api-id>.execute-api.<api-region>.amazonaws.com/<stage>/',
|
710 | hooks: {
|
711 | beforeRequest: [
|
712 | async options => {
|
713 | const credentials = await chain.resolvePromise();
|
714 | aws4.sign(options, credentials);
|
715 | }
|
716 | ]
|
717 | }
|
718 | });
|
719 |
|
720 | const response = await awsClient('endpoint/path', {
|
721 | // Request-specific options
|
722 | });
|
723 | ```
|
724 |
|
725 |
|
726 | ## Testing
|
727 |
|
728 | You can test your requests by using the [`nock`](https://github.com/node-nock/nock) module to mock an endpoint:
|
729 |
|
730 | ```js
|
731 | const got = require('got');
|
732 | const nock = require('nock');
|
733 |
|
734 | nock('https://sindresorhus.com')
|
735 | .get('/')
|
736 | .reply(200, 'Hello world!');
|
737 |
|
738 | (async () => {
|
739 | const response = await got('sindresorhus.com');
|
740 | console.log(response.body);
|
741 | //=> 'Hello world!'
|
742 | })();
|
743 | ```
|
744 |
|
745 | If you need real integration tests you can use [`create-test-server`](https://github.com/lukechilds/create-test-server):
|
746 |
|
747 | ```js
|
748 | const got = require('got');
|
749 | const createTestServer = require('create-test-server');
|
750 |
|
751 | (async () => {
|
752 | const server = await createTestServer();
|
753 | server.get('/', 'Hello world!');
|
754 |
|
755 | const response = await got(server.url);
|
756 | console.log(response.body);
|
757 | //=> 'Hello world!'
|
758 |
|
759 | await server.close();
|
760 | })();
|
761 | ```
|
762 |
|
763 |
|
764 | ## Tips
|
765 |
|
766 | ### User Agent
|
767 |
|
768 | It's a good idea to set the `'user-agent'` header so the provider can more easily see how their resource is used. By default, it's the URL to this repo. You can omit this header by setting it to `null`.
|
769 |
|
770 | ```js
|
771 | const got = require('got');
|
772 | const pkg = require('./package.json');
|
773 |
|
774 | got('sindresorhus.com', {
|
775 | headers: {
|
776 | 'user-agent': `my-module/${pkg.version} (https://github.com/username/my-module)`
|
777 | }
|
778 | });
|
779 |
|
780 | got('sindresorhus.com', {
|
781 | headers: {
|
782 | 'user-agent': null
|
783 | }
|
784 | });
|
785 | ```
|
786 |
|
787 | ### 304 Responses
|
788 |
|
789 | Bear in mind; if you send an `if-modified-since` header and receive a `304 Not Modified` response, the body will be empty. It's your responsibility to cache and retrieve the body contents.
|
790 |
|
791 | ### Custom endpoints
|
792 |
|
793 | Use `got.extend()` to make it nicer to work with REST APIs. Especially if you use the `baseUrl` option.
|
794 |
|
795 | **Note:** Not to be confused with [`got.create()`](advanced-creation.md), which has no defaults.
|
796 |
|
797 | ```js
|
798 | const got = require('got');
|
799 | const pkg = require('./package.json');
|
800 |
|
801 | const custom = got.extend({
|
802 | baseUrl: 'example.com',
|
803 | json: true,
|
804 | headers: {
|
805 | 'user-agent': `my-module/${pkg.version} (https://github.com/username/my-module)`
|
806 | }
|
807 | });
|
808 |
|
809 | // Use `custom` exactly how you use `got`
|
810 | (async () => {
|
811 | const list = await custom('/v1/users/list');
|
812 | })();
|
813 | ```
|
814 |
|
815 | *Need to merge some instances into a single one? Check out [`got.mergeInstances()`](advanced-creation.md#merging-instances).*
|
816 |
|
817 |
|
818 | ## Comparison
|
819 |
|
820 | | | `got` | `request` | `node-fetch` | `axios` |
|
821 | |-----------------------|:-------:|:---------:|:------------:|:-------:|
|
822 | | HTTP/2 support | ✖ | ✖ | ✖ | ✖ |
|
823 | | Browser support | ✖ | ✖ | ✔* | ✔ |
|
824 | | Electron support | ✔ | ✖ | ✖ | ✖ |
|
825 | | Promise API | ✔ | ✔ | ✔ | ✔ |
|
826 | | Stream API | ✔ | ✔ | ✖ | ✖ |
|
827 | | Request cancelation | ✔ | ✖ | ✖ | ✔ |
|
828 | | RFC compliant caching | ✔ | ✖ | ✖ | ✖ |
|
829 | | Follows redirects | ✔ | ✔ | ✔ | ✔ |
|
830 | | Retries on failure | ✔ | ✖ | ✖ | ✖ |
|
831 | | Progress events | ✔ | ✖ | ✖ | ✔ |
|
832 | | Handles gzip/deflate | ✔ | ✔ | ✔ | ✔ |
|
833 | | Advanced timeouts | ✔ | ✖ | ✖ | ✖ |
|
834 | | Errors with metadata | ✔ | ✖ | ✖ | ✔ |
|
835 | | JSON mode | ✔ | ✖ | ✖ | ✔ |
|
836 | | Custom defaults | ✔ | ✔ | ✖ | ✔ |
|
837 | | Composable | ✔ | ✖ | ✖ | ✖ |
|
838 | | Hooks | ✔ | ✖ | ✖ | ✔ |
|
839 | | Issues open | ![][gio] | ![][rio] | ![][nio] | ![][aio] |
|
840 | | Issues closed | ![][gic] | ![][ric] | ![][nic] | ![][aic] |
|
841 | | Downloads | ![][gd] | ![][rd] | ![][nd] | ![][ad] |
|
842 | | Coverage | ![][gc] | ![][rc] | ![][nc] | ![][ac] |
|
843 | | Build | ![][gb] | ![][rb] | ![][nb] | ![][ab] |
|
844 | | Dependents | ![][gdp] | ![][rdp] | ![][ndp] | ![][adp] |
|
845 | | Install size | ![][gis] | ![][ris] | ![][nis] | ![][ais] |
|
846 |
|
847 | \* It's almost API compatible with the browser `fetch` API.
|
848 |
|
849 |
|
850 | [gio]: https://img.shields.io/github/issues/sindresorhus/got.svg
|
851 | [rio]: https://img.shields.io/github/issues/request/request.svg
|
852 | [nio]: https://img.shields.io/github/issues/bitinn/node-fetch.svg
|
853 | [aio]: https://img.shields.io/github/issues/axios/axios.svg
|
854 |
|
855 |
|
856 | [gic]: https://img.shields.io/github/issues-closed/sindresorhus/got.svg
|
857 | [ric]: https://img.shields.io/github/issues-closed/request/request.svg
|
858 | [nic]: https://img.shields.io/github/issues-closed/bitinn/node-fetch.svg
|
859 | [aic]: https://img.shields.io/github/issues-closed/axios/axios.svg
|
860 |
|
861 |
|
862 | [gd]: https://img.shields.io/npm/dm/got.svg
|
863 | [rd]: https://img.shields.io/npm/dm/request.svg
|
864 | [nd]: https://img.shields.io/npm/dm/node-fetch.svg
|
865 | [ad]: https://img.shields.io/npm/dm/axios.svg
|
866 |
|
867 |
|
868 | [gc]: https://coveralls.io/repos/github/sindresorhus/got/badge.svg?branch=master
|
869 | [rc]: https://coveralls.io/repos/github/request/request/badge.svg?branch=master
|
870 | [nc]: https://coveralls.io/repos/github/bitinn/node-fetch/badge.svg?branch=master
|
871 | [ac]: https://coveralls.io/repos/github/mzabriskie/axios/badge.svg?branch=master
|
872 |
|
873 |
|
874 | [gb]: https://travis-ci.org/sindresorhus/got.svg?branch=master
|
875 | [rb]: https://travis-ci.org/request/request.svg?branch=master
|
876 | [nb]: https://travis-ci.org/bitinn/node-fetch.svg?branch=master
|
877 | [ab]: https://travis-ci.org/axios/axios.svg?branch=master
|
878 |
|
879 |
|
880 | [gdp]: https://badgen.net/npm/dependents/got
|
881 | [rdp]: https://badgen.net/npm/dependents/request
|
882 | [ndp]: https://badgen.net/npm/dependents/node-fetch
|
883 | [adp]: https://badgen.net/npm/dependents/axios
|
884 |
|
885 |
|
886 | [gis]: https://packagephobia.now.sh/badge?p=got
|
887 | [ris]: https://packagephobia.now.sh/badge?p=request
|
888 | [nis]: https://packagephobia.now.sh/badge?p=node-fetch
|
889 | [ais]: https://packagephobia.now.sh/badge?p=axios
|
890 |
|
891 |
|
892 | ## Related
|
893 |
|
894 | - [gh-got](https://github.com/sindresorhus/gh-got) - Got convenience wrapper to interact with the GitHub API
|
895 | - [gl-got](https://github.com/singapore/gl-got) - Got convenience wrapper to interact with the GitLab API
|
896 | - [travis-got](https://github.com/samverschueren/travis-got) - Got convenience wrapper to interact with the Travis API
|
897 | - [graphql-got](https://github.com/kevva/graphql-got) - Got convenience wrapper to interact with GraphQL
|
898 | - [GotQL](https://github.com/khaosdoctor/gotql) - Got convenience wrapper to interact with GraphQL using JSON-parsed queries instead of strings
|
899 |
|
900 |
|
901 | ## Maintainers
|
902 |
|
903 | [![Sindre Sorhus](https://github.com/sindresorhus.png?size=100)](https://sindresorhus.com) | [![Vsevolod Strukchinsky](https://github.com/floatdrop.png?size=100)](https://github.com/floatdrop) | [![Alexander Tesfamichael](https://github.com/AlexTes.png?size=100)](https://github.com/AlexTes) | [![Luke Childs](https://github.com/lukechilds.png?size=100)](https://github.com/lukechilds) | [![Szymon Marczak](https://github.com/szmarczak.png?size=100)](https://github.com/szmarczak) | [![Brandon Smith](https://github.com/brandon93s.png?size=100)](https://github.com/brandon93s)
|
904 | ---|---|---|---|---|---
|
905 | [Sindre Sorhus](https://sindresorhus.com) | [Vsevolod Strukchinsky](https://github.com/floatdrop) | [Alexander Tesfamichael](https://alextes.me) | [Luke Childs](https://github.com/lukechilds) | [Szymon Marczak](https://github.com/szmarczak) | [Brandon Smith](https://github.com/brandon93s)
|
906 |
|
907 |
|
908 | ## License
|
909 |
|
910 | MIT
|