UNPKG

7.02 kBMarkdownView Raw
1# gaxios
2
3[![npm version](https://img.shields.io/npm/v/gaxios.svg)](https://www.npmjs.org/package/gaxios)
4[![codecov](https://codecov.io/gh/googleapis/gaxios/branch/master/graph/badge.svg)](https://codecov.io/gh/googleapis/gaxios)
5[![Code Style: Google](https://img.shields.io/badge/code%20style-google-blueviolet.svg)](https://github.com/google/gts)
6
7> An HTTP request client that provides an `axios` like interface over top of `node-fetch`.
8
9## Install
10
11```sh
12$ npm install gaxios
13```
14
15## Example
16
17```js
18const {request} = require('gaxios');
19const res = await request({
20 url: 'https://www.googleapis.com/discovery/v1/apis/',
21});
22```
23
24## Setting Defaults
25
26Gaxios supports setting default properties both on the default instance, and on additional instances. This is often useful when making many requests to the same domain with the same base settings. For example:
27
28```js
29const gaxios = require('gaxios');
30gaxios.instance.defaults = {
31 baseURL: 'https://example.com'
32 headers: {
33 Authorization: 'SOME_TOKEN'
34 }
35}
36gaxios.request({url: '/data'}).then(...);
37```
38
39Note that setting default values will take precedence
40over other authentication methods, i.e., application default credentials.
41
42## Request Options
43
44```ts
45interface GaxiosOptions = {
46 // The url to which the request should be sent. Required.
47 url: string,
48
49 // The HTTP method to use for the request. Defaults to `GET`.
50 method: 'GET',
51
52 // The base Url to use for the request. Prepended to the `url` property above.
53 baseURL: 'https://example.com';
54
55 // The HTTP methods to be sent with the request.
56 headers: { 'some': 'header' },
57
58 // The data to send in the body of the request. Data objects will be
59 // serialized as JSON.
60 //
61 // Note: if you would like to provide a Content-Type header other than
62 // application/json you you must provide a string or readable stream, rather
63 // than an object:
64 // data: JSON.stringify({some: 'data'})
65 // data: fs.readFile('./some-data.jpeg')
66 data: {
67 some: 'data'
68 },
69
70 // The max size of the http response content in bytes allowed.
71 // Defaults to `0`, which is the same as unset.
72 maxContentLength: 2000,
73
74 // The max number of HTTP redirects to follow.
75 // Defaults to 100.
76 maxRedirects: 100,
77
78 // The querystring parameters that will be encoded using `qs` and
79 // appended to the url
80 params: {
81 querystring: 'parameters'
82 },
83
84 // By default, we use the `querystring` package in node core to serialize
85 // querystring parameters. You can override that and provide your
86 // own implementation.
87 paramsSerializer: (params) => {
88 return qs.stringify(params);
89 },
90
91 // The timeout for the HTTP request in milliseconds. Defaults to 0.
92 timeout: 1000,
93
94 // Optional method to override making the actual HTTP request. Useful
95 // for writing tests and instrumentation
96 adapter?: async (options, defaultAdapter) => {
97 const res = await defaultAdapter(options);
98 res.data = {
99 ...res.data,
100 extraProperty: 'your extra property',
101 };
102 return res;
103 };
104
105 // The expected return type of the request. Options are:
106 // json | stream | blob | arraybuffer | text | unknown
107 // Defaults to `unknown`.
108 responseType: 'unknown',
109
110 // The node.js http agent to use for the request.
111 agent: someHttpsAgent,
112
113 // Custom function to determine if the response is valid based on the
114 // status code. Defaults to (>= 200 && < 300)
115 validateStatus: (status: number) => true,
116
117 // Implementation of `fetch` to use when making the API call. By default,
118 // will use the browser context if available, and fall back to `node-fetch`
119 // in node.js otherwise.
120 fetchImplementation?: typeof fetch;
121
122 // Configuration for retrying of requests.
123 retryConfig: {
124 // The number of times to retry the request. Defaults to 3.
125 retry?: number;
126
127 // The number of retries already attempted.
128 currentRetryAttempt?: number;
129
130 // The HTTP Methods that will be automatically retried.
131 // Defaults to ['GET','PUT','HEAD','OPTIONS','DELETE']
132 httpMethodsToRetry?: string[];
133
134 // The HTTP response status codes that will automatically be retried.
135 // Defaults to: [[100, 199], [408, 408], [429, 429], [500, 599]]
136 statusCodesToRetry?: number[][];
137
138 // Function to invoke when a retry attempt is made.
139 onRetryAttempt?: (err: GaxiosError) => Promise<void> | void;
140
141 // Function to invoke which determines if you should retry
142 shouldRetry?: (err: GaxiosError) => Promise<boolean> | boolean;
143
144 // When there is no response, the number of retries to attempt. Defaults to 2.
145 noResponseRetries?: number;
146
147 // The amount of time to initially delay the retry, in ms. Defaults to 100ms.
148 retryDelay?: number;
149 },
150
151 // Enables default configuration for retries.
152 retry: boolean,
153
154 // Cancelling a request requires the `abort-controller` library.
155 // See https://github.com/bitinn/node-fetch#request-cancellation-with-abortsignal
156 signal?: AbortSignal
157
158 /**
159 * A collection of parts to send as a `Content-Type: multipart/related` request.
160 */
161 multipart?: GaxiosMultipartOptions;
162
163 /**
164 * An optional proxy to use for requests.
165 * Available via `process.env.HTTP_PROXY` and `process.env.HTTPS_PROXY` as well - with a preference for the this config option when multiple are available.
166 * The `agent` option overrides this.
167 *
168 * @see {@link GaxiosOptions.noProxy}
169 * @see {@link GaxiosOptions.agent}
170 */
171 proxy?: string | URL;
172 /**
173 * A list for excluding traffic for proxies.
174 * Available via `process.env.NO_PROXY` as well as a common-separated list of strings - merged with any local `noProxy` rules.
175 *
176 * - When provided a string, it is matched by
177 * - Wildcard `*.` and `.` matching are available. (e.g. `.example.com` or `*.example.com`)
178 * - When provided a URL, it is matched by the `.origin` property.
179 * - For example, requesting `https://example.com` with the following `noProxy`s would result in a no proxy use:
180 * - new URL('https://example.com')
181 * - new URL('https://example.com:443')
182 * - The following would be used with a proxy:
183 * - new URL('http://example.com:80')
184 * - new URL('https://example.com:8443')
185 * - When provided a regular expression it is used to match the stringified URL
186 *
187 * @see {@link GaxiosOptions.proxy}
188 */
189 noProxy?: (string | URL | RegExp)[];
190
191 /**
192 * An experimental, customizable error redactor.
193 *
194 * Set `false` to disable.
195 *
196 * @remarks
197 *
198 * This does not replace the requirement for an active Data Loss Prevention (DLP) provider. For DLP suggestions, see:
199 * - https://cloud.google.com/sensitive-data-protection/docs/redacting-sensitive-data#dlp_deidentify_replace_infotype-nodejs
200 * - https://cloud.google.com/sensitive-data-protection/docs/infotypes-reference#credentials_and_secrets
201 *
202 * @experimental
203 */
204 errorRedactor?: typeof defaultErrorRedactor | false;
205}
206```
207
208## License
209
210[Apache-2.0](https://github.com/googleapis/gaxios/blob/master/LICENSE)