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](#response) or a [stream](#streams-1) if `options.stream` is set to true.
|
93 |
|
94 | ##### url
|
95 |
|
96 | Type: `string` `Object`
|
97 |
|
98 | 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).
|
99 |
|
100 | Properties from `options` will override properties in the parsed `url`.
|
101 |
|
102 | If no protocol is specified, it will default to `https`.
|
103 |
|
104 | ##### options
|
105 |
|
106 | Type: `Object`
|
107 |
|
108 | Any of the [`https.request`](https://nodejs.org/api/https.html#https_https_request_options_callback) options.
|
109 |
|
110 | ###### baseUrl
|
111 |
|
112 | Type: `string` `Object`
|
113 |
|
114 | When specified, `url` will be prepended by `baseUrl`.<br>
|
115 | If you specify an absolute URL, it will skip the `baseUrl`.
|
116 |
|
117 | Very useful when used with `got.extend()` to create niche-specific Got instances.
|
118 |
|
119 | Can be a string or a [WHATWG `URL`](https://nodejs.org/api/url.html#url_class_url).
|
120 |
|
121 | Backslash at the end of `baseUrl` and at the beginning of the `url` argument is optional:
|
122 |
|
123 | ```js
|
124 | await got('hello', {baseUrl: 'https://example.com/v1'});
|
125 | //=> 'https://example.com/v1/hello'
|
126 |
|
127 | await got('/hello', {baseUrl: 'https://example.com/v1/'});
|
128 | //=> 'https://example.com/v1/hello'
|
129 |
|
130 | await got('/hello', {baseUrl: 'https://example.com/v1'});
|
131 | //=> 'https://example.com/v1/hello'
|
132 | ```
|
133 |
|
134 | ###### headers
|
135 |
|
136 | Type: `Object`<br>
|
137 | Default: `{}`
|
138 |
|
139 | Request headers.
|
140 |
|
141 | Existing headers will be overwritten. Headers set to `null` will be omitted.
|
142 |
|
143 | ###### stream
|
144 |
|
145 | Type: `boolean`<br>
|
146 | Default: `false`
|
147 |
|
148 | Returns a `Stream` instead of a `Promise`. This is equivalent to calling `got.stream(url, [options])`.
|
149 |
|
150 | ###### body
|
151 |
|
152 | Type: `string` `Buffer` `stream.Readable` [`form-data` instance](https://github.com/form-data/form-data)
|
153 |
|
154 | *If you provide this option, `got.stream()` will be read-only.*
|
155 |
|
156 | The body that will be sent with a `POST` request.
|
157 |
|
158 | If present in `options` and `options.method` is not set, `options.method` will be set to `POST`.
|
159 |
|
160 | 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`.
|
161 |
|
162 | ###### cookieJar
|
163 |
|
164 | Type: [`tough.CookieJar` instance](https://github.com/salesforce/tough-cookie#cookiejar)
|
165 |
|
166 | Cookie support. You don't have to care about parsing or how to store them. [Example.](#cookies)
|
167 |
|
168 | **Note:** `options.headers.cookie` will be overridden.
|
169 |
|
170 | ###### encoding
|
171 |
|
172 | Type: `string` `null`<br>
|
173 | Default: `'utf8'`
|
174 |
|
175 | [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).
|
176 |
|
177 | ###### form
|
178 |
|
179 | Type: `boolean`<br>
|
180 | Default: `false`
|
181 |
|
182 | *If you provide this option, `got.stream()` will be read-only.*
|
183 |
|
184 | If set to `true` and `Content-Type` header is not set, it will be set to `application/x-www-form-urlencoded`.
|
185 |
|
186 | `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).
|
187 |
|
188 | ###### json
|
189 |
|
190 | Type: `boolean`<br>
|
191 | Default: `false`
|
192 |
|
193 | *If you use `got.stream()`, this option will be ignored.*
|
194 |
|
195 | If set to `true` and `Content-Type` header is not set, it will be set to `application/json`.
|
196 |
|
197 | 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.
|
198 |
|
199 | `body` must be a plain object or array and will be stringified.
|
200 |
|
201 | ###### query
|
202 |
|
203 | Type: `string` `Object` [`URLSearchParams`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
|
204 |
|
205 | Query string object that will be added to the request URL. This will override the query string in `url`.
|
206 |
|
207 | ###### timeout
|
208 |
|
209 | Type: `number` `Object`
|
210 |
|
211 | 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.
|
212 |
|
213 | This also accepts an `object` with the following fields to constrain the duration of each phase of the request lifecycle:
|
214 |
|
215 | - `lookup` starts when a socket is assigned and ends when the hostname has been resolved. Does not apply when using a Unix domain socket.
|
216 | - `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.
|
217 | - `secureConnect` starts when `connect` completes and ends when the handshaking process completes (HTTPS only).
|
218 | - `socket` starts when the socket is connected. See [request.setTimeout](https://nodejs.org/api/http.html#http_request_settimeout_timeout_callback).
|
219 | - `response` starts when the request has been written to the socket and ends when the response headers are received.
|
220 | - `send` starts when the socket is connected and ends with the request has been written to the socket.
|
221 | - `request` starts when the request is initiated and ends when the response's end event fires.
|
222 |
|
223 | ###### retry
|
224 |
|
225 | Type: `number` `Object`<br>
|
226 | Default:
|
227 | - retries: `2`
|
228 | - methods: `GET` `PUT` `HEAD` `DELETE` `OPTIONS` `TRACE`
|
229 | - 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)
|
230 | - maxRetryAfter: `undefined`
|
231 |
|
232 | 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.
|
233 |
|
234 | If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`.<br>
|
235 | 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.
|
236 |
|
237 | Delays between retries counts with function `1000 * Math.pow(2, retry) + Math.random() * 100`, where `retry` is attempt number (starts from 0).
|
238 |
|
239 | 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).
|
240 |
|
241 | **Note:** It retries only on the specified methods, status codes, and on these network errors:
|
242 | - `ETIMEDOUT`: One of the [timeout](#timeout) limits were reached.
|
243 | - `ECONNRESET`: Connection was forcibly closed by a peer.
|
244 | - `EADDRINUSE`: Could not bind to any free port.
|
245 | - `ECONNREFUSED`: Connection was refused by the server.
|
246 | - `EPIPE`: The remote side of the stream being written has been closed.
|
247 |
|
248 | ###### followRedirect
|
249 |
|
250 | Type: `boolean`<br>
|
251 | Default: `true`
|
252 |
|
253 | Defines if redirect responses should be followed automatically.
|
254 |
|
255 | 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).
|
256 |
|
257 | ###### decompress
|
258 |
|
259 | Type: `boolean`<br>
|
260 | Default: `true`
|
261 |
|
262 | Decompress the response automatically. This will set the `accept-encoding` header to `gzip, deflate` unless you set it yourself.
|
263 |
|
264 | 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.
|
265 |
|
266 | ###### cache
|
267 |
|
268 | Type: `Object`<br>
|
269 | Default: `false`
|
270 |
|
271 | [Cache adapter instance](#cache-adapters) for storing cached data.
|
272 |
|
273 | ###### request
|
274 |
|
275 | Type: `Function`<br>
|
276 | Default: `http.request` `https.request` *(depending on the protocol)*
|
277 |
|
278 | Custom request function. The main purpose of this is to [support HTTP2 using a wrapper](#experimental-http2-support).
|
279 |
|
280 | ###### useElectronNet
|
281 |
|
282 | Type: `boolean`<br>
|
283 | Default: `false`
|
284 |
|
285 | 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).
|
286 |
|
287 | ###### throwHttpErrors
|
288 |
|
289 | Type: `boolean`<br>
|
290 | Default: `true`
|
291 |
|
292 | Determines if a `got.HTTPError` is thrown for error responses (non-2xx status codes).
|
293 |
|
294 | 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.
|
295 |
|
296 | ###### agent
|
297 |
|
298 | Same as the [`agent` option](https://nodejs.org/api/http.html#http_http_request_url_options_callback) for `http.request`, but with an extra feature:
|
299 |
|
300 | 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.
|
301 |
|
302 | ```js
|
303 | const got = require('got');
|
304 | const HttpAgent = require('agentkeepalive');
|
305 | const {HttpsAgent} = HttpAgent;
|
306 |
|
307 | got('sindresorhus.com', {
|
308 | agent: {
|
309 | http: new HttpAgent(),
|
310 | https: new HttpsAgent()
|
311 | }
|
312 | });
|
313 | ```
|
314 |
|
315 | ###### hooks
|
316 |
|
317 | Type: `Object<string, Function[]>`<br>
|
318 | Default: `{beforeRequest: []}`
|
319 |
|
320 | Hooks allow modifications during the request lifecycle. Hook functions may be async and are run serially.
|
321 |
|
322 | ###### hooks.beforeRequest
|
323 |
|
324 | Type: `Function[]`<br>
|
325 | Default: `[]`
|
326 |
|
327 | 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.
|
328 |
|
329 | See the [AWS section](#aws) for an example.
|
330 |
|
331 | **Note**: Modifying the `body` is not recommended because the `content-length` header has already been computed and assigned.
|
332 |
|
333 | #### Response
|
334 |
|
335 | 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.
|
336 |
|
337 | ##### body
|
338 |
|
339 | Type: `string` `Object` *(depending on `options.json`)*
|
340 |
|
341 | The result of the request.
|
342 |
|
343 | ##### url
|
344 |
|
345 | Type: `string`
|
346 |
|
347 | The request URL or the final URL after redirects.
|
348 |
|
349 | ##### requestUrl
|
350 |
|
351 | Type: `string`
|
352 |
|
353 | The original request URL.
|
354 |
|
355 | ##### timings
|
356 |
|
357 | Type: `Object`
|
358 |
|
359 | The object contains the following properties:
|
360 |
|
361 | - `start` - Time when the request started.
|
362 | - `socket` - Time when a socket was assigned to the request.
|
363 | - `lookup` - Time when the DNS lookup finished.
|
364 | - `connect` - Time when the socket successfully connected.
|
365 | - `upload` - Time when the request finished uploading.
|
366 | - `response` - Time when the request fired the `response` event.
|
367 | - `end` - Time when the response fired the `end` event.
|
368 | - `error` - Time when the request fired the `error` event.
|
369 | - `phases`
|
370 | - `wait` - `timings.socket - timings.start`
|
371 | - `dns` - `timings.lookup - timings.socket`
|
372 | - `tcp` - `timings.connect - timings.lookup`
|
373 | - `request` - `timings.upload - timings.connect`
|
374 | - `firstByte` - `timings.response - timings.upload`
|
375 | - `download` - `timings.end - timings.response`
|
376 | - `total` - `timings.end - timings.start` or `timings.error - timings.start`
|
377 |
|
378 | **Note**: The time is a `number` representing the milliseconds elapsed since the UNIX epoch.
|
379 |
|
380 | ##### fromCache
|
381 |
|
382 | Type: `boolean`
|
383 |
|
384 | Whether the response was retrieved from the cache.
|
385 |
|
386 | ##### redirectUrls
|
387 |
|
388 | Type: `Array`
|
389 |
|
390 | The redirect URLs.
|
391 |
|
392 | ##### retryCount
|
393 |
|
394 | Type: `number`
|
395 |
|
396 | The number of times the request was retried.
|
397 |
|
398 | #### Streams
|
399 |
|
400 | **Note**: Progress events, redirect events and request/response events can also be used with promises.
|
401 |
|
402 | #### got.stream(url, [options])
|
403 |
|
404 | Sets `options.stream` to `true`.
|
405 |
|
406 | Returns a [duplex stream](https://nodejs.org/api/stream.html#stream_class_stream_duplex) with additional events:
|
407 |
|
408 | ##### .on('request', request)
|
409 |
|
410 | `request` event to get the request object of the request.
|
411 |
|
412 | **Tip**: You can use `request` event to abort request:
|
413 |
|
414 | ```js
|
415 | got.stream('github.com')
|
416 | .on('request', request => setTimeout(() => request.abort(), 50));
|
417 | ```
|
418 |
|
419 | ##### .on('response', response)
|
420 |
|
421 | The `response` event to get the response object of the final request.
|
422 |
|
423 | ##### .on('redirect', response, nextOptions)
|
424 |
|
425 | The `redirect` event to get the response object of a redirect. The second argument is options for the next request to the redirect location.
|
426 |
|
427 | ##### .on('uploadProgress', progress)
|
428 | ##### .on('downloadProgress', progress)
|
429 |
|
430 | Progress events for uploading (sending a request) and downloading (receiving a response). The `progress` argument is an object like:
|
431 |
|
432 | ```js
|
433 | {
|
434 | percent: 0.1,
|
435 | transferred: 1024,
|
436 | total: 10240
|
437 | }
|
438 | ```
|
439 |
|
440 | If it's not possible to retrieve the body size (can happen when streaming), `total` will be `null`.
|
441 |
|
442 | ```js
|
443 | (async () => {
|
444 | const response = await got('sindresorhus.com')
|
445 | .on('downloadProgress', progress => {
|
446 | // Report download progress
|
447 | })
|
448 | .on('uploadProgress', progress => {
|
449 | // Report upload progress
|
450 | });
|
451 |
|
452 | console.log(response);
|
453 | })();
|
454 | ```
|
455 |
|
456 | ##### .on('error', error, body, response)
|
457 |
|
458 | 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.
|
459 |
|
460 | #### got.get(url, [options])
|
461 | #### got.post(url, [options])
|
462 | #### got.put(url, [options])
|
463 | #### got.patch(url, [options])
|
464 | #### got.head(url, [options])
|
465 | #### got.delete(url, [options])
|
466 |
|
467 | Sets `options.method` to the method name and makes a request.
|
468 |
|
469 | ### Instances
|
470 |
|
471 | #### got.extend([options])
|
472 |
|
473 | Configure a new `got` instance with default `options`. `options` are merged with the parent instance's `defaults.options` using [`got.mergeOptions`](#gotmergeoptionsparentoptions-newoptions).
|
474 |
|
475 | ```js
|
476 | const client = got.extend({
|
477 | baseUrl: 'https://example.com',
|
478 | headers: {
|
479 | 'x-unicorn': 'rainbow'
|
480 | }
|
481 | });
|
482 |
|
483 | client.get('/demo');
|
484 |
|
485 | /* HTTP Request =>
|
486 | * GET /demo HTTP/1.1
|
487 | * Host: example.com
|
488 | * x-unicorn: rainbow
|
489 | */
|
490 | ```
|
491 |
|
492 | ```js
|
493 | (async () => {
|
494 | const client = got.extend({
|
495 | baseUrl: 'httpbin.org',
|
496 | headers: {
|
497 | 'x-foo': 'bar'
|
498 | }
|
499 | });
|
500 | const {headers} = (await client.get('/headers', {json: true})).body;
|
501 | //=> headers['x-foo'] === 'bar'
|
502 |
|
503 | const jsonClient = client.extend({
|
504 | json: true,
|
505 | headers: {
|
506 | 'x-baz': 'qux'
|
507 | }
|
508 | });
|
509 | const {headers: headers2} = (await jsonClient.get('/headers')).body;
|
510 | //=> headers2['x-foo'] === 'bar'
|
511 | //=> headers2['x-baz'] === 'qux'
|
512 | })();
|
513 | ```
|
514 |
|
515 | *Need more control over the behavior of Got? Check out the [`got.create()`](advanced-creation.md).*
|
516 |
|
517 | #### got.mergeOptions(parentOptions, newOptions)
|
518 |
|
519 | 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:
|
520 |
|
521 | ```js
|
522 | const a = {headers: {cat: 'meow', wolf: ['bark', 'wrrr']}};
|
523 | const b = {headers: {cow: 'moo', wolf: ['auuu']}};
|
524 |
|
525 | {...a, ...b} // => {headers: {cow: 'moo', wolf: ['auuu']}}
|
526 | got.mergeOptions(a, b) // => {headers: {cat: 'meow', cow: 'moo', wolf: ['auuu']}}
|
527 | ```
|
528 |
|
529 | Options are deeply merged to a new object. The value of each key is determined as follows:
|
530 |
|
531 | - If the new property is set to `undefined`, it keeps the old one.
|
532 | - 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).
|
533 | - If the new property is a plain `Object`:
|
534 | - If the parent property is a plain `Object` too, both values are merged recursively into a new `Object`.
|
535 | - Otherwise, only the new value is deeply cloned.
|
536 | - If the new property is an `Array`, it overwrites the old one with a deep clone of the new property.
|
537 | - Otherwise, the new value is assigned to the key.
|
538 |
|
539 | ## Errors
|
540 |
|
541 | Each error contains (if available) `statusCode`, `statusMessage`, `host`, `hostname`, `method`, `path`, `protocol` and `url` properties to make debugging easier.
|
542 |
|
543 | In Promise mode, the `response` is attached to the error.
|
544 |
|
545 | #### got.CacheError
|
546 |
|
547 | When a cache method fails, for example, if the database goes down or there's a filesystem error.
|
548 |
|
549 | #### got.RequestError
|
550 |
|
551 | When a request fails. Contains a `code` property with error class code, like `ECONNREFUSED`.
|
552 |
|
553 | #### got.ReadError
|
554 |
|
555 | When reading from response stream fails.
|
556 |
|
557 | #### got.ParseError
|
558 |
|
559 | When `json` option is enabled, server response code is 2xx, and `JSON.parse` fails.
|
560 |
|
561 | #### got.HTTPError
|
562 |
|
563 | When the server response code is not 2xx. Includes `statusCode`, `statusMessage`, and `redirectUrls` properties.
|
564 |
|
565 | #### got.MaxRedirectsError
|
566 |
|
567 | 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.
|
568 |
|
569 | #### got.UnsupportedProtocolError
|
570 |
|
571 | When given an unsupported protocol.
|
572 |
|
573 | #### got.CancelError
|
574 |
|
575 | When the request is aborted with `.cancel()`.
|
576 |
|
577 | #### got.TimeoutError
|
578 |
|
579 | When the request is aborted due to a [timeout](#timeout)
|
580 |
|
581 | ## Aborting the request
|
582 |
|
583 | The promise returned by Got has a [`.cancel()`](https://github.com/sindresorhus/p-cancelable) method which when called, aborts the request.
|
584 |
|
585 | ```js
|
586 | (async () => {
|
587 | const request = got(url, options);
|
588 |
|
589 | // …
|
590 |
|
591 | // In another part of the code
|
592 | if (something) {
|
593 | request.cancel();
|
594 | }
|
595 |
|
596 | // …
|
597 |
|
598 | try {
|
599 | await request;
|
600 | } catch (error) {
|
601 | if (request.isCanceled) { // Or `error instanceof got.CancelError`
|
602 | // Handle cancelation
|
603 | }
|
604 |
|
605 | // Handle other errors
|
606 | }
|
607 | })();
|
608 | ```
|
609 |
|
610 | <a name="cache-adapters"></a>
|
611 | ## Cache
|
612 |
|
613 | 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).
|
614 |
|
615 | You can use the JavaScript `Map` type as an in-memory cache:
|
616 |
|
617 | ```js
|
618 | const got = require('got');
|
619 | const map = new Map();
|
620 |
|
621 | (async () => {
|
622 | let response = await got('sindresorhus.com', {cache: map});
|
623 | console.log(response.fromCache);
|
624 | //=> false
|
625 |
|
626 | response = await got('sindresorhus.com', {cache: map});
|
627 | console.log(response.fromCache);
|
628 | //=> true
|
629 | })();
|
630 | ```
|
631 |
|
632 | 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):
|
633 |
|
634 | ```
|
635 | $ npm install @keyv/redis
|
636 | ```
|
637 |
|
638 | ```js
|
639 | const got = require('got');
|
640 | const KeyvRedis = require('@keyv/redis');
|
641 |
|
642 | const redis = new KeyvRedis('redis://user:pass@localhost:6379');
|
643 |
|
644 | got('sindresorhus.com', {cache: redis});
|
645 | ```
|
646 |
|
647 | Got supports anything that follows the Map API, so it's easy to write your own storage adapter or use a third-party solution.
|
648 |
|
649 | For example, the following are all valid storage adapters:
|
650 |
|
651 | ```js
|
652 | const storageAdapter = new Map();
|
653 | // Or
|
654 | const storageAdapter = require('./my-storage-adapter');
|
655 | // Or
|
656 | const QuickLRU = require('quick-lru');
|
657 | const storageAdapter = new QuickLRU({maxSize: 1000});
|
658 |
|
659 | got('sindresorhus.com', {cache: storageAdapter});
|
660 | ```
|
661 |
|
662 | View the [Keyv docs](https://github.com/lukechilds/keyv) for more information on how to use storage adapters.
|
663 |
|
664 |
|
665 | ## Proxies
|
666 |
|
667 | You can use the [`tunnel`](https://github.com/koichik/node-tunnel) package with the `agent` option to work with proxies:
|
668 |
|
669 | ```js
|
670 | const got = require('got');
|
671 | const tunnel = require('tunnel-agent');
|
672 |
|
673 | got('sindresorhus.com', {
|
674 | agent: tunnel.httpOverHttp({
|
675 | proxy: {
|
676 | host: 'localhost'
|
677 | }
|
678 | })
|
679 | });
|
680 | ```
|
681 |
|
682 | 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.
|
683 |
|
684 |
|
685 | ## Cookies
|
686 |
|
687 | You can use the [`tough-cookie`](https://github.com/salesforce/tough-cookie) package:
|
688 |
|
689 | ```js
|
690 | const got = require('got');
|
691 | const {CookieJar} = require('tough-cookie');
|
692 |
|
693 | const cookieJar = new CookieJar();
|
694 | cookieJar.setCookie('foo=bar', 'https://www.google.com');
|
695 |
|
696 | got('google.com', {cookieJar});
|
697 | ```
|
698 |
|
699 |
|
700 | ## Form data
|
701 |
|
702 | You can use the [`form-data`](https://github.com/form-data/form-data) package to create POST request with form data:
|
703 |
|
704 | ```js
|
705 | const fs = require('fs');
|
706 | const got = require('got');
|
707 | const FormData = require('form-data');
|
708 | const form = new FormData();
|
709 |
|
710 | form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
|
711 |
|
712 | got.post('google.com', {
|
713 | body: form
|
714 | });
|
715 | ```
|
716 |
|
717 |
|
718 | ## OAuth
|
719 |
|
720 | You can use the [`oauth-1.0a`](https://github.com/ddo/oauth-1.0a) package to create a signed OAuth request:
|
721 |
|
722 | ```js
|
723 | const got = require('got');
|
724 | const crypto = require('crypto');
|
725 | const OAuth = require('oauth-1.0a');
|
726 |
|
727 | const oauth = OAuth({
|
728 | consumer: {
|
729 | key: process.env.CONSUMER_KEY,
|
730 | secret: process.env.CONSUMER_SECRET
|
731 | },
|
732 | signature_method: 'HMAC-SHA1',
|
733 | hash_function: (baseString, key) => crypto.createHmac('sha1', key).update(baseString).digest('base64')
|
734 | });
|
735 |
|
736 | const token = {
|
737 | key: process.env.ACCESS_TOKEN,
|
738 | secret: process.env.ACCESS_TOKEN_SECRET
|
739 | };
|
740 |
|
741 | const url = 'https://api.twitter.com/1.1/statuses/home_timeline.json';
|
742 |
|
743 | got(url, {
|
744 | headers: oauth.toHeader(oauth.authorize({url, method: 'GET'}, token)),
|
745 | json: true
|
746 | });
|
747 | ```
|
748 |
|
749 |
|
750 | ## Unix Domain Sockets
|
751 |
|
752 | 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`.
|
753 |
|
754 | - `PROTOCOL` - `http` or `https` *(optional)*
|
755 | - `SOCKET` - Absolute path to a unix domain socket, for example: `/var/run/docker.sock`
|
756 | - `PATH` - Request path, for example: `/v2/keys`
|
757 |
|
758 | ```js
|
759 | got('http://unix:/var/run/docker.sock:/containers/json');
|
760 |
|
761 | // Or without protocol (HTTP by default)
|
762 | got('unix:/var/run/docker.sock:/containers/json');
|
763 | ```
|
764 |
|
765 |
|
766 | ## AWS
|
767 |
|
768 | 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.
|
769 |
|
770 | ```js
|
771 | const AWS = require('aws-sdk');
|
772 | const aws4 = require('aws4');
|
773 | const got = require('got');
|
774 |
|
775 | const chain = new AWS.CredentialProviderChain();
|
776 |
|
777 | // Create a Got instance to use relative paths and signed requests
|
778 | const awsClient = got.extend({
|
779 | baseUrl: 'https://<api-id>.execute-api.<api-region>.amazonaws.com/<stage>/',
|
780 | hooks: {
|
781 | beforeRequest: [
|
782 | async options => {
|
783 | const credentials = await chain.resolvePromise();
|
784 | aws4.sign(options, credentials);
|
785 | }
|
786 | ]
|
787 | }
|
788 | });
|
789 |
|
790 | const response = await awsClient('endpoint/path', {
|
791 | // Request-specific options
|
792 | });
|
793 | ```
|
794 |
|
795 |
|
796 | ## Testing
|
797 |
|
798 | You can test your requests by using the [`nock`](https://github.com/node-nock/nock) package to mock an endpoint:
|
799 |
|
800 | ```js
|
801 | const got = require('got');
|
802 | const nock = require('nock');
|
803 |
|
804 | nock('https://sindresorhus.com')
|
805 | .get('/')
|
806 | .reply(200, 'Hello world!');
|
807 |
|
808 | (async () => {
|
809 | const response = await got('sindresorhus.com');
|
810 | console.log(response.body);
|
811 | //=> 'Hello world!'
|
812 | })();
|
813 | ```
|
814 |
|
815 | If you need real integration tests you can use [`create-test-server`](https://github.com/lukechilds/create-test-server):
|
816 |
|
817 | ```js
|
818 | const got = require('got');
|
819 | const createTestServer = require('create-test-server');
|
820 |
|
821 | (async () => {
|
822 | const server = await createTestServer();
|
823 | server.get('/', 'Hello world!');
|
824 |
|
825 | const response = await got(server.url);
|
826 | console.log(response.body);
|
827 | //=> 'Hello world!'
|
828 |
|
829 | await server.close();
|
830 | })();
|
831 | ```
|
832 |
|
833 |
|
834 | ## Tips
|
835 |
|
836 | ### User Agent
|
837 |
|
838 | 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`.
|
839 |
|
840 | ```js
|
841 | const got = require('got');
|
842 | const pkg = require('./package.json');
|
843 |
|
844 | got('sindresorhus.com', {
|
845 | headers: {
|
846 | 'user-agent': `my-package/${pkg.version} (https://github.com/username/my-package)`
|
847 | }
|
848 | });
|
849 |
|
850 | got('sindresorhus.com', {
|
851 | headers: {
|
852 | 'user-agent': null
|
853 | }
|
854 | });
|
855 | ```
|
856 |
|
857 | ### 304 Responses
|
858 |
|
859 | 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.
|
860 |
|
861 | ### Custom endpoints
|
862 |
|
863 | Use `got.extend()` to make it nicer to work with REST APIs. Especially if you use the `baseUrl` option.
|
864 |
|
865 | **Note:** Not to be confused with [`got.create()`](advanced-creation.md), which has no defaults.
|
866 |
|
867 | ```js
|
868 | const got = require('got');
|
869 | const pkg = require('./package.json');
|
870 |
|
871 | const custom = got.extend({
|
872 | baseUrl: 'example.com',
|
873 | json: true,
|
874 | headers: {
|
875 | 'user-agent': `my-package/${pkg.version} (https://github.com/username/my-package)`
|
876 | }
|
877 | });
|
878 |
|
879 | // Use `custom` exactly how you use `got`
|
880 | (async () => {
|
881 | const list = await custom('/v1/users/list');
|
882 | })();
|
883 | ```
|
884 |
|
885 | *Need to merge some instances into a single one? Check out [`got.mergeInstances()`](advanced-creation.md#merging-instances).*
|
886 |
|
887 | ### Experimental HTTP2 support
|
888 |
|
889 | Got provides an experimental support for HTTP2 using the [`http2-wrapper`](https://github.com/szmarczak/http2-wrapper) package:
|
890 |
|
891 | ```js
|
892 | const got = require('got');
|
893 | const {request} = require('http2-wrapper');
|
894 |
|
895 | const h2got = got.extend({request});
|
896 |
|
897 | (async () => {
|
898 | const {body} = await h2got('https://nghttp2.org/httpbin/headers');
|
899 | console.log(body);
|
900 | })();
|
901 | ```
|
902 |
|
903 | ## Comparison
|
904 |
|
905 | | | `got` | `request` | `node-fetch` | `axios` |
|
906 | |-----------------------|:------------:|:------------:|:------------:|:------------:|
|
907 | | HTTP/2 support | ❔ | ✖ | ✖ | ✖ |
|
908 | | Browser support | ✖ | ✖ | ✔* | ✔ |
|
909 | | Electron support | ✔ | ✖ | ✖ | ✖ |
|
910 | | Promise API | ✔ | ✔ | ✔ | ✔ |
|
911 | | Stream API | ✔ | ✔ | ✖ | ✖ |
|
912 | | Request cancelation | ✔ | ✖ | ✖ | ✔ |
|
913 | | RFC compliant caching | ✔ | ✖ | ✖ | ✖ |
|
914 | | Cookies (out-of-box) | ✔ | ✔ | ✖ | ✖ |
|
915 | | Follows redirects | ✔ | ✔ | ✔ | ✔ |
|
916 | | Retries on failure | ✔ | ✖ | ✖ | ✖ |
|
917 | | Progress events | ✔ | ✖ | ✖ | Browser only |
|
918 | | Handles gzip/deflate | ✔ | ✔ | ✔ | ✔ |
|
919 | | Advanced timeouts | ✔ | ✖ | ✖ | ✖ |
|
920 | | Timings | ✔ | ✔ | ✖ | ✖ |
|
921 | | Errors with metadata | ✔ | ✖ | ✖ | ✔ |
|
922 | | JSON mode | ✔ | ✔ | ✖ | ✔ |
|
923 | | Custom defaults | ✔ | ✔ | ✖ | ✔ |
|
924 | | Composable | ✔ | ✖ | ✖ | ✖ |
|
925 | | Hooks | ✔ | ✖ | ✖ | ✔ |
|
926 | | Issues open | ![][gio] | ![][rio] | ![][nio] | ![][aio] |
|
927 | | Issues closed | ![][gic] | ![][ric] | ![][nic] | ![][aic] |
|
928 | | Downloads | ![][gd] | ![][rd] | ![][nd] | ![][ad] |
|
929 | | Coverage | ![][gc] | ![][rc] | ![][nc] | ![][ac] |
|
930 | | Build | ![][gb] | ![][rb] | ![][nb] | ![][ab] |
|
931 | | Bugs | ![][gbg] | ![][rbg] | ![][nbg] | ![][abg] |
|
932 | | Dependents | ![][gdp] | ![][rdp] | ![][ndp] | ![][adp] |
|
933 | | Install size | ![][gis] | ![][ris] | ![][nis] | ![][ais] |
|
934 |
|
935 | \* It's almost API compatible with the browser `fetch` API.<br>
|
936 | ❔ Experimental support.
|
937 |
|
938 |
|
939 | [gio]: https://img.shields.io/github/issues/sindresorhus/got.svg
|
940 | [rio]: https://img.shields.io/github/issues/request/request.svg
|
941 | [nio]: https://img.shields.io/github/issues/bitinn/node-fetch.svg
|
942 | [aio]: https://img.shields.io/github/issues/axios/axios.svg
|
943 |
|
944 |
|
945 | [gic]: https://img.shields.io/github/issues-closed/sindresorhus/got.svg
|
946 | [ric]: https://img.shields.io/github/issues-closed/request/request.svg
|
947 | [nic]: https://img.shields.io/github/issues-closed/bitinn/node-fetch.svg
|
948 | [aic]: https://img.shields.io/github/issues-closed/axios/axios.svg
|
949 |
|
950 |
|
951 | [gd]: https://img.shields.io/npm/dm/got.svg
|
952 | [rd]: https://img.shields.io/npm/dm/request.svg
|
953 | [nd]: https://img.shields.io/npm/dm/node-fetch.svg
|
954 | [ad]: https://img.shields.io/npm/dm/axios.svg
|
955 |
|
956 |
|
957 | [gc]: https://coveralls.io/repos/github/sindresorhus/got/badge.svg?branch=master
|
958 | [rc]: https://coveralls.io/repos/github/request/request/badge.svg?branch=master
|
959 | [nc]: https://coveralls.io/repos/github/bitinn/node-fetch/badge.svg?branch=master
|
960 | [ac]: https://coveralls.io/repos/github/mzabriskie/axios/badge.svg?branch=master
|
961 |
|
962 |
|
963 | [gb]: https://travis-ci.org/sindresorhus/got.svg?branch=master
|
964 | [rb]: https://travis-ci.org/request/request.svg?branch=master
|
965 | [nb]: https://travis-ci.org/bitinn/node-fetch.svg?branch=master
|
966 | [ab]: https://travis-ci.org/axios/axios.svg?branch=master
|
967 |
|
968 |
|
969 | [gbg]: https://badgen.net/github/label-issues/sindresorhus/got/bug/open
|
970 | [rbg]: https://badgen.net/github/label-issues/request/request/Needs%20investigation/open
|
971 | [nbg]: https://badgen.net/github/label-issues/bitinn/node-fetch/bug/open
|
972 | [abg]: https://badgen.net/github/label-issues/axios/axios/bug/open
|
973 |
|
974 |
|
975 | [gdp]: https://badgen.net/npm/dependents/got
|
976 | [rdp]: https://badgen.net/npm/dependents/request
|
977 | [ndp]: https://badgen.net/npm/dependents/node-fetch
|
978 | [adp]: https://badgen.net/npm/dependents/axios
|
979 |
|
980 |
|
981 | [gis]: https://packagephobia.now.sh/badge?p=got
|
982 | [ris]: https://packagephobia.now.sh/badge?p=request
|
983 | [nis]: https://packagephobia.now.sh/badge?p=node-fetch
|
984 | [ais]: https://packagephobia.now.sh/badge?p=axios
|
985 |
|
986 |
|
987 | ## Related
|
988 |
|
989 | - [gh-got](https://github.com/sindresorhus/gh-got) - Got convenience wrapper to interact with the GitHub API
|
990 | - [gl-got](https://github.com/singapore/gl-got) - Got convenience wrapper to interact with the GitLab API
|
991 | - [travis-got](https://github.com/samverschueren/travis-got) - Got convenience wrapper to interact with the Travis API
|
992 | - [graphql-got](https://github.com/kevva/graphql-got) - Got convenience wrapper to interact with GraphQL
|
993 | - [GotQL](https://github.com/khaosdoctor/gotql) - Got convenience wrapper to interact with GraphQL using JSON-parsed queries instead of strings
|
994 |
|
995 |
|
996 | ## Maintainers
|
997 |
|
998 | [![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)
|
999 | ---|---|---|---|---|---
|
1000 | [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)
|
1001 |
|
1002 |
|
1003 | ## License
|
1004 |
|
1005 | MIT
|