UNPKG

26.7 kBMarkdownView Raw
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) [![Build status: Windows](https://ci.appveyor.com/api/projects/status/a9fgfqojj8mf5upf/branch/master?svg=true)](https://ci.appveyor.com/project/sindresorhus/got/branch/master) [![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)
17
18A nicer interface to the built-in [`http`](http://nodejs.org/api/http.html) module.
19
20Created because [`request`](https://github.com/request/request) is bloated *(several megabytes!)*.
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
39
40## Install
41
42```
43$ npm install got
44```
45
46<a href="https://www.patreon.com/sindresorhus">
47 <img src="https://c5.patreon.com/external/logo/become_a_patron_button@2x.png" width="160">
48</a>
49
50
51## Usage
52
53```js
54const got = require('got');
55
56(async () => {
57 try {
58 const response = await got('sindresorhus.com');
59 console.log(response.body);
60 //=> '<!doctype html> ...'
61 } catch (error) {
62 console.log(error.response.body);
63 //=> 'Internal server error ...'
64 }
65})();
66```
67
68###### Streams
69
70```js
71const fs = require('fs');
72const got = require('got');
73
74got.stream('sindresorhus.com').pipe(fs.createWriteStream('index.html'));
75
76// For POST, PUT, and PATCH methods `got.stream` returns a `stream.Writable`
77fs.createReadStream('index.html').pipe(got.stream.post('sindresorhus.com'));
78```
79
80
81### API
82
83It's a `GET` request by default, but can be changed by using different methods or in the `options`.
84
85#### got(url, [options])
86
87Returns 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.
88
89The response object will normally 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 [responselike object](https://github.com/lukechilds/responselike) which behaves in the same way.
90
91The response will also have a `fromCache` property set with a boolean value.
92
93##### url
94
95Type: `string` `Object`
96
97The URL to request as simple string, a [`https.request` options](https://nodejs.org/api/https.html#https_https_request_options_callback), or a [WHATWG `URL`](https://nodejs.org/api/url.html#url_class_url).
98
99Properties from `options` will override properties in the parsed `url`.
100
101If no protocol is specified, it will default to `https`.
102
103##### options
104
105Type: `Object`
106
107Any of the [`https.request`](https://nodejs.org/api/https.html#https_https_request_options_callback) options.
108
109###### baseUrl
110
111Type: `string` `Object`
112
113When specified, `url` will be prepended by `baseUrl`.<br>
114If you specify an absolute URL, it will skip the `baseUrl`.
115
116Very useful when used with `got.extend()` to create niche-specific `got` instances.
117
118Can be a string or a [WHATWG `URL`](https://nodejs.org/api/url.html#url_class_url).
119
120###### headers
121
122Type: `Object`<br>
123Default: `{}`
124
125Request headers.
126
127Existing headers will be overwritten. Headers set to `null` will be omitted.
128
129###### stream
130
131Type: `boolean`<br>
132Default: `false`
133
134Returns a `Stream` instead of a `Promise`. This is equivalent to calling `got.stream(url, [options])`.
135
136###### body
137
138Type: `string` `Buffer` `stream.Readable` [`form-data` instance](https://github.com/form-data/form-data)
139
140*If you provide this option, `got.stream()` will be read-only.*
141
142Body that will be sent with a `POST` request.
143
144If present in `options` and `options.method` is not set, `options.method` will be set to `POST`.
145
146The `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`.
147
148###### encoding
149
150Type: `string` `null`<br>
151Default: `'utf8'`
152
153[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).
154
155###### form
156
157Type: `boolean`<br>
158Default: `false`
159
160*If you provide this option, `got.stream()` will be read-only.*
161
162If set to `true` and `Content-Type` header is not set, it will be set to `application/x-www-form-urlencoded`.
163
164`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).
165
166###### json
167
168Type: `boolean`<br>
169Default: `false`
170
171*If you use `got.stream()`, this option will be ignored.*
172
173If set to `true` and `Content-Type` header is not set, it will be set to `application/json`.
174
175Parse 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.
176
177`body` must be a plain object or array and will be stringified.
178
179###### query
180
181Type: `string` `Object`<br>
182
183Query string object that will be added to the request URL. This will override the query string in `url`.
184
185###### timeout
186
187Type: `number` `Object`
188
189Milliseconds to wait for the server to end the response before aborting request with [`got.TimeoutError`](#gottimeouterror) error (a.k.a. `request` property). By default there's no timeout.
190
191This also accepts an `object` with the following fields to constrain the duration of each phase of the request lifecycle:
192
193- `lookup` starts when a socket is assigned and ends when the hostname has been resolved. Does not apply when using a Unix domain socket.
194- `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.
195- `secureConnect` starts when `connect` completes and ends when the handshaking process completes (HTTPS only).
196- `socket` starts when the socket is connected. See [request.setTimeout](https://nodejs.org/api/http.html#http_request_settimeout_timeout_callback).
197- `response` starts when the request has been written to the socket and ends when the response headers are received.
198- `send` starts when the socket is connected and ends with the request has been written to the socket.
199- `request` starts when the request is initiated and ends when the response's end event fires.
200
201###### retry
202
203Type: `number` `Object`<br>
204Default:
205- retries: `2`
206- methods: `GET` `PUT` `HEAD` `DELETE` `OPTIONS` `TRACE`
207- 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) [`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)
208- maxRetryAfter: `undefined`
209
210Object representing `retries`, `methods`, `statusCodes` and `maxRetryAfter` fields for 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.
211
212If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`.<br>
213If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will cancel the request.
214
215Delays between retries counts with function `1000 * Math.pow(2, retry) + Math.random() * 100`, where `retry` is attempt number (starts from 0).
216
217Option `retries` can be a `number`, but also accepts a `function` with `retry` and `error` arguments. Function must return delay in milliseconds (`0` return value cancels retry).
218
219**Note:** It retries only on the specified methods, status codes, and on these network errors:
220- `ETIMEDOUT`: One of the [timeout](#timeout) limits was reached.
221- `ECONNRESET`: Connection was forcibly closed by a peer.
222- `EADDRINUSE`: Could not bind to any free port.
223- `ECONNREFUSED`: Connection was refused by the server.
224- `EPIPE`: The remote side of the stream being written has been closed.
225
226###### followRedirect
227
228Type: `boolean`<br>
229Default: `true`
230
231Defines if redirect responses should be followed automatically.
232
233Note that if a `303` is sent by the server in response to any request type (`POST`, `DELETE`, etc.), got will automatically
234request 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).
235
236###### decompress
237
238Type: `boolean`<br>
239Default: `true`
240
241Decompress the response automatically. This will set the `accept-encoding` header to `gzip, deflate` unless you set it yourself.
242
243If 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.
244
245###### cache
246
247Type: `Object`<br>
248Default: `false`
249
250[Cache adapter instance](#cache-adapters) for storing cached data.
251
252###### useElectronNet
253
254Type: `boolean`<br>
255Default: `false`
256
257When 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).
258
259###### throwHttpErrors
260
261Type: `boolean`<br>
262Default: `true`
263
264Determines if a `got.HTTPError` is thrown for error responses (non-2xx status codes).
265
266If 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.
267
268###### hooks
269
270Type: `Object<string, Array<Function>>`<br>
271Default: `{ beforeRequest: [] }`
272
273Hooks allow modifications during the request lifecycle. Hook functions may be async and are run serially.
274
275###### hooks.beforeRequest
276
277Type: `Array<Function>`<br>
278Default: `[]`
279
280Called 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 uses HMAC-signing.
281
282See the [AWS section](#aws) for an example.
283
284**Note**: Modifying the `body` is not recommended because the `content-length` header has already been computed and assigned.
285
286#### Streams
287
288**Note**: Progress events, redirect events and request/response events can also be used with promises.
289
290#### got.stream(url, [options])
291
292Sets `options.stream` to `true`.
293
294`stream` method will return Duplex stream with additional events:
295
296##### .on('request', request)
297
298`request` event to get the request object of the request.
299
300**Tip**: You can use `request` event to abort request:
301
302```js
303got.stream('github.com')
304 .on('request', req => setTimeout(() => req.abort(), 50));
305```
306
307##### .on('response', response)
308
309`response` event to get the response object of the final request.
310
311##### .on('redirect', response, nextOptions)
312
313`redirect` event to get the response object of a redirect. The second argument is options for the next request to the redirect location.
314
315##### .on('uploadProgress', progress)
316##### .on('downloadProgress', progress)
317
318Progress events for uploading (sending request) and downloading (receiving response). The `progress` argument is an object like:
319
320```js
321{
322 percent: 0.1,
323 transferred: 1024,
324 total: 10240
325}
326```
327
328If it's not possible to retrieve the body size (can happen when streaming), `total` will be `null`.
329
330```js
331(async () => {
332 const response = await got('sindresorhus.com')
333 .on('downloadProgress', progress => {
334 // Report download progress
335 })
336 .on('uploadProgress', progress => {
337 // Report upload progress
338 });
339
340 console.log(response);
341})();
342```
343
344##### .on('error', error, body, response)
345
346`error` event emitted in case of 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 response object.
347
348#### got.get(url, [options])
349#### got.post(url, [options])
350#### got.put(url, [options])
351#### got.patch(url, [options])
352#### got.head(url, [options])
353#### got.delete(url, [options])
354
355Sets `options.method` to the method name and makes a request.
356
357### Instances
358
359#### got.extend([options])
360
361Configure a new `got` instance with default `options`. `options` are merged with the parent instance's `defaults.options` using [`got.mergeOptions`](#gotmergeoptionsparentoptions-newoptions).
362
363
364```js
365const client = got.extend({
366 baseUrl: 'https://example.com',
367 headers: {
368 'x-unicorn': 'rainbow'
369 }
370});
371
372client.get('/demo');
373
374/* HTTP Request =>
375 * GET /demo HTTP/1.1
376 * Host: example.com
377 * x-unicorn: rainbow
378 */
379 ```
380
381```js
382(async () => {
383 const client = got.extend({
384 baseUrl: 'httpbin.org',
385 headers: {
386 'x-foo': 'bar'
387 }
388 });
389 const {headers} = (await client.get('/headers', {json: true})).body;
390 //=> headers['x-foo'] === 'bar'
391
392 const jsonClient = client.extend({
393 json: true,
394 headers: {
395 'x-baz': 'qux'
396 }
397 });
398 const {headers: headers2} = (await jsonClient.get('/headers')).body;
399 //=> headers2['x-foo'] === 'bar'
400 //=> headers2['x-baz'] === 'qux'
401})();
402```
403
404*Need more control over the behavior of Got? Check out the [`got.create()`](advanced-creation.md).*
405
406#### got.mergeOptions(parentOptions, newOptions)
407
408Extends 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:
409
410```js
411const a = {headers: {cat: 'meow', wolf: ['bark', 'wrrr']}};
412const b = {headers: {cow: 'moo', wolf: ['auuu']}};
413
414{...a, ...b} // => {headers: {cow: 'moo', wolf: ['auuu']}}
415got.mergeOptions(a, b) // => {headers: {cat: 'meow', cow: 'moo', wolf: ['auuu']}}
416```
417
418Options are deeply merged to a new object. The value of each key is determined as follows:
419
420- If the new property is set to `undefined`, it keeps the old one.
421- 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).
422- If the new property is a plain `Object`:
423 - If the parent property is a plain `Object` too, both values are merged recursively into a new `Object`.
424 - Otherwise, only the new value is deeply cloned.
425- If the new property is an `Array`, it overwrites the old one with a deep clone of the new property.
426- Otherwise, the new value is assigned to the key.
427
428## Errors
429
430Each error contains (if available) `statusCode`, `statusMessage`, `host`, `hostname`, `method`, `path`, `protocol` and `url` properties to make debugging easier.
431
432In Promise mode, the `response` is attached to the error.
433
434#### got.CacheError
435
436When a cache method fails, for example if the database goes down, or there's a filesystem error.
437
438#### got.RequestError
439
440When a request fails. Contains a `code` property with error class code, like `ECONNREFUSED`.
441
442#### got.ReadError
443
444When reading from response stream fails.
445
446#### got.ParseError
447
448When `json` option is enabled, server response code is 2xx, and `JSON.parse` fails.
449
450#### got.HTTPError
451
452When server response code is not 2xx. Includes `statusCode`, `statusMessage`, and `redirectUrls` properties.
453
454#### got.MaxRedirectsError
455
456When server redirects you more than 10 times. Includes a `redirectUrls` property, which is an array of the URLs Got was redirected to before giving up.
457
458#### got.UnsupportedProtocolError
459
460When given an unsupported protocol.
461
462#### got.CancelError
463
464When the request is aborted with `.cancel()`.
465
466#### got.TimeoutError
467
468When the request is aborted due to a [timeout](#timeout)
469
470## Aborting the request
471
472The promise returned by Got has a [`.cancel()`](https://github.com/sindresorhus/p-cancelable) method which, when called, aborts the request.
473
474```js
475(async () => {
476 const request = got(url, options);
477
478
479
480 // In another part of the code
481 if (something) {
482 request.cancel();
483 }
484
485
486
487 try {
488 await request;
489 } catch (error) {
490 if (request.isCanceled) { // Or `error instanceof got.CancelError`
491 // Handle cancelation
492 }
493
494 // Handle other errors
495 }
496})();
497```
498
499<a name="cache-adapters"></a>
500## Cache
501
502Got implements [RFC 7234](http://httpwg.org/specs/rfc7234.html) compliant HTTP caching which works out of the box in memory or is easily pluggable with a wide range of storage adapters. Fresh cache entries are served directly from cache and stale cache entries are revalidated with `If-None-Match`/`If-Modified-Since` headers. You can read more about the underlying cache behaviour in the `cacheable-request` [documentation](https://github.com/lukechilds/cacheable-request).
503
504You can use the JavaScript `Map` type as an in memory cache:
505
506```js
507const got = require('got');
508const map = new Map();
509
510(async () => {
511 let response = await got('sindresorhus.com', {cache: map});
512 console.log(response.fromCache);
513 //=> false
514
515 response = await got('sindresorhus.com', {cache: map});
516 console.log(response.fromCache);
517 //=> true
518})();
519```
520
521Got 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):
522
523```
524$ npm install @keyv/redis
525```
526
527```js
528const got = require('got');
529const KeyvRedis = require('@keyv/redis');
530
531const redis = new KeyvRedis('redis://user:pass@localhost:6379');
532
533got('sindresorhus.com', {cache: redis});
534```
535
536Got supports anything that follows the Map API, so it's easy to write your own storage adapter or use a third-party solution.
537
538For example, the following are all valid storage adapters:
539
540```js
541const storageAdapter = new Map();
542// or
543const storageAdapter = require('./my-storage-adapter');
544// or
545const QuickLRU = require('quick-lru');
546const storageAdapter = new QuickLRU({maxSize: 1000});
547
548got('sindresorhus.com', {cache: storageAdapter});
549```
550
551View the [Keyv docs](https://github.com/lukechilds/keyv) for more information on how to use storage adapters.
552
553
554## Proxies
555
556You can use the [`tunnel`](https://github.com/koichik/node-tunnel) module with the `agent` option to work with proxies:
557
558```js
559const got = require('got');
560const tunnel = require('tunnel-agent');
561
562got('sindresorhus.com', {
563 agent: tunnel.httpOverHttp({
564 proxy: {
565 host: 'localhost'
566 }
567 })
568});
569```
570
571If 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.
572
573```js
574const got = require('got');
575const HttpAgent = require('agentkeepalive');
576const HttpsAgent = HttpAgent.HttpsAgent;
577
578got('sindresorhus.com', {
579 agent: {
580 http: new HttpAgent(),
581 https: new HttpsAgent()
582 }
583});
584```
585
586
587## Cookies
588
589You can use the [`cookie`](https://github.com/jshttp/cookie) module to include cookies in a request:
590
591```js
592const got = require('got');
593const cookie = require('cookie');
594
595got('google.com', {
596 headers: {
597 cookie: cookie.serialize('foo', 'bar')
598 }
599});
600
601got('google.com', {
602 headers: {
603 cookie: [
604 cookie.serialize('foo', 'bar'),
605 cookie.serialize('fizz', 'buzz')
606 ].join(';')
607 }
608});
609```
610
611
612## Form data
613
614You can use the [`form-data`](https://github.com/form-data/form-data) module to create POST request with form data:
615
616```js
617const fs = require('fs');
618const got = require('got');
619const FormData = require('form-data');
620const form = new FormData();
621
622form.append('my_file', fs.createReadStream('/foo/bar.jpg'));
623
624got.post('google.com', {
625 body: form
626});
627```
628
629
630## OAuth
631
632You can use the [`oauth-1.0a`](https://github.com/ddo/oauth-1.0a) module to create a signed OAuth request:
633
634```js
635const got = require('got');
636const crypto = require('crypto');
637const OAuth = require('oauth-1.0a');
638
639const oauth = OAuth({
640 consumer: {
641 key: process.env.CONSUMER_KEY,
642 secret: process.env.CONSUMER_SECRET
643 },
644 signature_method: 'HMAC-SHA1',
645 hash_function: (baseString, key) => crypto.createHmac('sha1', key).update(baseString).digest('base64')
646});
647
648const token = {
649 key: process.env.ACCESS_TOKEN,
650 secret: process.env.ACCESS_TOKEN_SECRET
651};
652
653const url = 'https://api.twitter.com/1.1/statuses/home_timeline.json';
654
655got(url, {
656 headers: oauth.toHeader(oauth.authorize({url, method: 'GET'}, token)),
657 json: true
658});
659```
660
661
662## Unix Domain Sockets
663
664Requests 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`.
665
666- `PROTOCOL` - `http` or `https` *(optional)*
667- `SOCKET` - absolute path to a unix domain socket, e.g. `/var/run/docker.sock`
668- `PATH` - request path, e.g. `/v2/keys`
669
670```js
671got('http://unix:/var/run/docker.sock:/containers/json');
672
673// or without protocol (http by default)
674got('unix:/var/run/docker.sock:/containers/json');
675```
676
677
678## AWS
679
680Requests 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.
681
682```js
683const AWS = require('aws-sdk');
684const aws4 = require('aws4');
685const got = require('got');
686
687const credentials = await new AWS.CredentialProviderChain().resolvePromise();
688
689// Create a Got instance to use relative paths and signed requests
690const awsClient = got.extend(
691 {
692 baseUrl: 'https://<api-id>.execute-api.<api-region>.amazonaws.com/<stage>/',
693 hooks: {
694 beforeRequest: [
695 async options => {
696 await credentials.getPromise();
697 aws4.sign(options, credentials);
698 }
699 ]
700 }
701 }
702);
703
704const response = await awsClient('endpoint/path', {
705 // Request-specific options
706});
707```
708
709
710## Testing
711
712You can test your requests by using the [`nock`](https://github.com/node-nock/nock) module to mock an endpoint:
713
714```js
715const got = require('got');
716const nock = require('nock');
717
718nock('https://sindresorhus.com')
719 .get('/')
720 .reply(200, 'Hello world!');
721
722(async () => {
723 const response = await got('sindresorhus.com');
724 console.log(response.body);
725 //=> 'Hello world!'
726})();
727```
728
729If you need real integration tests you can use [`create-test-server`](https://github.com/lukechilds/create-test-server):
730
731```js
732const got = require('got');
733const createTestServer = require('create-test-server');
734
735(async () => {
736 const server = await createTestServer();
737 server.get('/', 'Hello world!');
738
739 const response = await got(server.url);
740 console.log(response.body);
741 //=> 'Hello world!'
742
743 await server.close();
744})();
745```
746
747
748## Tips
749
750### User Agent
751
752It'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`.
753
754```js
755const got = require('got');
756const pkg = require('./package.json');
757
758got('sindresorhus.com', {
759 headers: {
760 'user-agent': `my-module/${pkg.version} (https://github.com/username/my-module)`
761 }
762});
763
764got('sindresorhus.com', {
765 headers: {
766 'user-agent': null
767 }
768});
769```
770
771### 304 Responses
772
773Bear 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.
774
775### Custom endpoints
776
777Use `got.extend()` to make it nicer to work with REST APIs. Especially if you use the `baseUrl` option.
778
779**Note:** Not to be confused with [`got.create()`](advanced-creation.md), which has no defaults.
780
781```js
782const got = require('got');
783const pkg = require('./package.json');
784
785const custom = got.extend({
786 baseUrl: 'example.com',
787 json: true,
788 headers: {
789 'user-agent': `my-module/${pkg.version} (https://github.com/username/my-module)`
790 }
791});
792
793// Use `custom` exactly how you use `got`
794(async () => {
795 const list = await custom('/v1/users/list');
796})();
797```
798
799
800## Related
801
802- [gh-got](https://github.com/sindresorhus/gh-got) - Got convenience wrapper to interact with the GitHub API
803- [gl-got](https://github.com/singapore/gl-got) - Got convenience wrapper to interact with the GitLab API
804- [travis-got](https://github.com/samverschueren/travis-got) - Got convenience wrapper to interact with the Travis API
805- [graphql-got](https://github.com/kevva/graphql-got) - Got convenience wrapper to interact with GraphQL
806- [GotQL](https://github.com/khaosdoctor/gotql) - Got convenience wrapper to interact with GraphQL using JSON-parsed queries instead of strings
807
808
809## Maintainers
810
811[![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)
812---|---|---|---|---|---
813[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)
814
815
816## License
817
818MIT