UNPKG

10.6 kBMarkdownView Raw
1# superagent
2
3[![build status](https://img.shields.io/travis/visionmedia/superagent.svg)](https://travis-ci.org/visionmedia/superagent)
4[![code coverage](https://img.shields.io/codecov/c/github/visionmedia/superagent.svg)](https://codecov.io/gh/visionmedia/superagent)
5[![code style](https://img.shields.io/badge/code_style-XO-5ed9c7.svg)](https://github.com/sindresorhus/xo)
6[![styled with prettier](https://img.shields.io/badge/styled_with-prettier-ff69b4.svg)](https://github.com/prettier/prettier)
7[![made with lass](https://img.shields.io/badge/made_with-lass-95CC28.svg)](https://lass.js.org)
8[![license](https://img.shields.io/github/license/visionmedia/superagent.svg)](LICENSE)
9
10> Small progressive client-side HTTP request library, and Node.js module with the same API, supporting many high-level HTTP client features
11
12
13## Table of Contents
14
15* [Install](#install)
16* [Usage](#usage)
17 * [Node](#node)
18 * [Browser](#browser)
19* [Supported Platforms](#supported-platforms)
20 * [Required Browser Features](#required-browser-features)
21* [Plugins](#plugins)
22* [Upgrading from previous versions](#upgrading-from-previous-versions)
23* [Contributors](#contributors)
24* [License](#license)
25
26
27## Install
28
29[npm][]:
30
31```sh
32npm install superagent
33```
34
35[yarn][]:
36
37```sh
38yarn add superagent
39```
40
41
42## Usage
43
44### Node
45
46```js
47const superagent = require('superagent');
48
49// callback
50superagent
51 .post('/api/pet')
52 .send({ name: 'Manny', species: 'cat' }) // sends a JSON post body
53 .set('X-API-Key', 'foobar')
54 .set('accept', 'json')
55 .end((err, res) => {
56 // Calling the end function will send the request
57 });
58
59// promise with then/catch
60superagent.post('/api/pet').then(console.log).catch(console.error);
61
62// promise with async/await
63(async () => {
64 try {
65 const res = await superagent.post('/api/pet');
66 console.log(res);
67 } catch (err) {
68 console.error(err);
69 }
70})();
71```
72
73### Browser
74
75**The browser-ready, minified version of `superagent` is only 6 KB (minified and gzipped)!**
76
77Browser-ready versions of this module are available via [jsdelivr][], [unpkg][], and also in the `node_modules/superagent/dist` folder in downloads of the `superagent` package.
78
79> Note that we also provide unminified versions with `.js` instead of `.min.js` file extensions.
80
81#### VanillaJS
82
83This is the solution for you if you're just using `<script>` tags everywhere!
84
85```html
86<script src="https://polyfill.io/v3/polyfill.min.js?features=Array.from,Promise,Symbol,Object.setPrototypeOf,Object.getOwnPropertySymbols,Set,Math.trunc,BigInt,Map,Reflect,WeakMap,WeakRef,WeakSet,BigInt,Map,Reflect,WeakMap,WeakRef,WeakSet"></script>
87<script src="https://cdn.jsdelivr.net/npm/superagent"></script>
88<!-- if you wish to use unpkg.com instead: -->
89<!-- <script src="https://unpkg.com/superagent"></script> -->
90<script type="text/javascript">
91 (function() {
92 // superagent is exposed as `window.superagent`
93 // if you wish to use "request" instead please
94 // uncomment the following line of code:
95 // `window.request = superagent;`
96 superagent
97 .post('/api/pet')
98 .send({ name: 'Manny', species: 'cat' }) // sends a JSON post body
99 .set('X-API-Key', 'foobar')
100 .set('accept', 'json')
101 .end(function (err, res) {
102 // Calling the end function will send the request
103 });
104 })();
105</script>
106```
107
108#### Bundler
109
110If you are using [browserify][], [webpack][], [rollup][], or another bundler, then you can follow the same usage as [Node](#node) above.
111
112
113## Supported Platforms
114
115* Node: v6.x+
116* Browsers (see [.browserslistrc](.browserslistrc)):
117
118 ```sh
119 npx browserslist
120 ```
121
122 ```sh
123 and_chr 71
124 and_ff 64
125 and_qq 1.2
126 and_uc 11.8
127 android 67
128 android 4.4.3-4.4.4
129 baidu 7.12
130 bb 10
131 bb 7
132 chrome 73
133 chrome 72
134 chrome 71
135 edge 18
136 edge 17
137 firefox 66
138 firefox 65
139 ie 11
140 ie 10
141 ie 9
142 ie_mob 11
143 ie_mob 10
144 ios_saf 12.0-12.1
145 ios_saf 11.3-11.4
146 op_mini all
147 op_mob 46
148 op_mob 12.1
149 opera 58
150 opera 57
151 safari 12
152 safari 11.1
153 samsung 8.2
154 samsung 7.2-7.4
155 ```
156
157### Required Browser Features
158
159We recommend using <https://polyfill.io> (specifically with the bundle mentioned in [VanillaJS](#vanillajs) above):
160
161```html
162<script src="https://polyfill.io/v3/polyfill.min.js?features=Array.from,Promise,Symbol,Object.setPrototypeOf,Object.getOwnPropertySymbols,Set,Math.trunc,BigInt,Map,Reflect,WeakMap,WeakRef,WeakSet"></script>
163```
164
165* IE 9-10 requires a polyfill for `Promise`, `Array.from`, `Symbol`, `Object.getOwnPropertySymbols`, and `Object.setPrototypeOf`
166* IE 9 requires a polyfill for `window.FormData` (we recommend [formdata-polyfill][]), `Set`, `Math.trunc`, `BigInt`, `Map`, `Reflect`, `WeakMap`, `WeakRef`, and `WeakSet`
167
168
169## Plugins
170
171SuperAgent is easily extended via plugins.
172
173```js
174const nocache = require('superagent-no-cache');
175const superagent = require('superagent');
176const prefix = require('superagent-prefix')('/static');
177
178superagent
179 .get('/some-url')
180 .query({ action: 'edit', city: 'London' }) // query string
181 .use(prefix) // Prefixes *only* this request
182 .use(nocache) // Prevents caching of *only* this request
183 .end((err, res) => {
184 // Do something
185 });
186```
187
188Existing plugins:
189
190* [superagent-no-cache](https://github.com/johntron/superagent-no-cache) - prevents caching by including Cache-Control header
191* [superagent-prefix](https://github.com/johntron/superagent-prefix) - prefixes absolute URLs (useful in test environment)
192* [superagent-suffix](https://github.com/timneutkens1/superagent-suffix) - suffix URLs with a given path
193* [superagent-mock](https://github.com/M6Web/superagent-mock) - simulate HTTP calls by returning data fixtures based on the requested URL
194* [superagent-mocker](https://github.com/shuvalov-anton/superagent-mocker) — simulate REST API
195* [superagent-cache](https://github.com/jpodwys/superagent-cache) - A global SuperAgent patch with built-in, flexible caching
196* [superagent-cache-plugin](https://github.com/jpodwys/superagent-cache-plugin) - A SuperAgent plugin with built-in, flexible caching
197* [superagent-jsonapify](https://github.com/alex94puchades/superagent-jsonapify) - A lightweight [json-api](http://jsonapi.org/format/) client addon for superagent
198* [superagent-serializer](https://github.com/zzarcon/superagent-serializer) - Converts server payload into different cases
199* [superagent-httpbackend](https://www.npmjs.com/package/superagent-httpbackend) - stub out requests using AngularJS' $httpBackend syntax
200* [superagent-throttle](https://github.com/leviwheatcroft/superagent-throttle) - queues and intelligently throttles requests
201* [superagent-charset](https://github.com/magicdawn/superagent-charset) - add charset support for node's SuperAgent
202* [superagent-verbose-errors](https://github.com/jcoreio/superagent-verbose-errors) - include response body in error messages for failed requests
203* [superagent-declare](https://github.com/damoclark/superagent-declare) - A simple [declarative](https://en.wikipedia.org/wiki/Declarative_programming) API for SuperAgent
204* [superagent-node-http-timings](https://github.com/webuniverseio/superagent-node-http-timings) - measure http timings in node.js
205
206Please prefix your plugin with `superagent-*` so that it can easily be found by others.
207
208For SuperAgent extensions such as couchdb and oauth visit the [wiki](https://github.com/visionmedia/superagent/wiki).
209
210
211## Upgrading from previous versions
212
213Please see [GitHub releases page](https://github.com/visionmedia/superagent/releases) for the current changelog.
214
215Our breaking changes are mostly in rarely used functionality and from stricter error handling.
216
217* [6.0 to 6.1](https://github.com/visionmedia/superagent/releases/tag/v6.1.0)
218 * Browser behaviour changed to match Node when serializing `application/x-www-form-urlencoded`, using `arrayFormat: 'indices'` semantics of `qs` library. (See: <https://www.npmjs.com/package/qs#stringifying>)
219* [5.x to 6.x](https://github.com/visionmedia/superagent/releases/tag/v6.0.0):
220 * Retry behavior is still opt-in, however we now have a more fine-grained list of status codes and error codes that we retry against (see updated docs)
221 * A specific issue with Content-Type matching not being case-insensitive is fixed
222 * Set is now required for IE 9, see [Required Browser Features](#required-browser-features) for more insight
223* [4.x to 5.x](https://github.com/visionmedia/superagent/releases/tag/v5.0.0):
224 * We've implemented the build setup of [Lass](https://lass.js.org) to simplify our stack and linting
225 * Unminified browserified build size has been reduced from 48KB to 20KB (via `tinyify` and the latest version of Babel using `@babel/preset-env` and `.browserslistrc`)
226 * Linting support has been added using `caniuse-lite` and `eslint-plugin-compat`
227 * We can now target what versions of Node we wish to support more easily using `.babelrc`
228* [3.x to 4.x](https://github.com/visionmedia/superagent/releases/tag/v4.0.0-alpha.1):
229 * Ensure you're running Node 6 or later. We've dropped support for Node 4.
230 * We've started using ES6 and for compatibility with Internet Explorer you may need to use Babel.
231 * We suggest migrating from `.end()` callbacks to `.then()` or `await`.
232* [2.x to 3.x](https://github.com/visionmedia/superagent/releases/tag/v3.0.0):
233 * Ensure you're running Node 4 or later. We've dropped support for Node 0.x.
234 * Test code that calls `.send()` multiple times. Invalid calls to `.send()` will now throw instead of sending garbage.
235* [1.x to 2.x](https://github.com/visionmedia/superagent/releases/tag/v2.0.0):
236 * If you use `.parse()` in the *browser* version, rename it to `.serialize()`.
237 * If you rely on `undefined` in query-string values being sent literally as the text "undefined", switch to checking for missing value instead. `?key=undefined` is now `?key` (without a value).
238 * If you use `.then()` in Internet Explorer, ensure that you have a polyfill that adds a global `Promise` object.
239* 0.x to 1.x:
240 * Instead of 1-argument callback `.end(function(res){})` use `.then(res => {})`.
241
242
243## Contributors
244
245| Name |
246| ------------------- |
247| **Kornel Lesiński** |
248| **Peter Lyons** |
249| **Hunter Loftis** |
250| **Nick Baugh** |
251
252
253## License
254
255[MIT](LICENSE) © TJ Holowaychuk
256
257
258##
259
260[npm]: https://www.npmjs.com/
261
262[yarn]: https://yarnpkg.com/
263
264[formdata-polyfill]: https://www.npmjs.com/package/formdata-polyfill
265
266[jsdelivr]: https://www.jsdelivr.com/
267
268[unpkg]: https://unpkg.com/
269
270[browserify]: https://github.com/browserify/browserify
271
272[webpack]: https://github.com/webpack/webpack
273
274[rollup]: https://github.com/rollup/rollup