superagent README

The project's README from github.com/forwardemail/superagent. As one markdown file: README.md.

superagent

build status code coverage code style styled with prettier made with lass license

Small progressive client-side HTTP request library, and Node.js module with the same API, supporting many high-level HTTP client features. Maintained for Forward Email and Lad.

Table of Contents

Install

npm:

npm install superagent

yarn:

yarn add superagent

Usage

Node

const superagent = require('superagent');

// callback
superagent
  .post('/api/pet')
  .send({ name: 'Manny', species: 'cat' }) // sends a JSON post body
  .set('X-API-Key', 'foobar')
  .set('accept', 'json')
  .end((err, res) => {
    // Calling the end function will send the request
  });

// promise with then/catch
superagent.post('/api/pet').then(console.log).catch(console.error);

// promise with async/await
(async () => {
  try {
    const res = await superagent.post('/api/pet');
    console.log(res);
  } catch (err) {
    console.error(err);
  }
})();

Browser

The browser-ready, minified version of superagent is only 50 KB (minified and gzipped).

Browser-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.

Note that we also provide unminified versions with .js instead of .min.js file extensions.

VanillaJS

This is the solution for you if you're just using <script> tags everywhere!

<script src="https://cdnjs.cloudflare.com/polyfill/v3/polyfill.min.js?features=WeakRef,BigInt"></script>
<script src="https://cdn.jsdelivr.net/npm/superagent"></script>
<!-- if you wish to use unpkg.com instead: -->
<!-- <script src="https://unpkg.com/superagent"></script> -->
<script type="text/javascript">
  (function() {
    // superagent is exposed as `window.superagent`
    // if you wish to use "request" instead please
    // uncomment the following line of code:
    // `window.request = superagent;`
    superagent
      .post('/api/pet')
      .send({ name: 'Manny', species: 'cat' }) // sends a JSON post body
      .set('X-API-Key', 'foobar')
      .set('accept', 'json')
      .end(function (err, res) {
        // Calling the end function will send the request
      });
  })();
</script>

Bundler

If you are using browserify, webpack, rollup, or another bundler, then you can follow the same usage as Node above.

Supported Platforms

Required Browser Features

We recommend using https://cdnjs.cloudflare.com/polyfill/ (specifically with the bundle mentioned in VanillaJS above):

<script src="https://cdnjs.cloudflare.com/polyfill/v3/polyfill.min.js?features=WeakRef,BigInt"></script>

Plugins

SuperAgent is easily extended via plugins.

const nocache = require('superagent-no-cache');
const superagent = require('superagent');
const prefix = require('superagent-prefix')('/static');

superagent
  .get('/some-url')
  .query({ action: 'edit', city: 'London' }) // query string
  .use(prefix) // Prefixes *only* this request
  .use(nocache) // Prevents caching of *only* this request
  .end((err, res) => {
    // Do something
  });

Existing plugins:

Please prefix your plugin with superagent-* so that it can easily be found by others.

For SuperAgent extensions such as couchdb and oauth visit the wiki.

Upgrading from previous versions

Please see GitHub releases page for the current changelog.

Our breaking changes are mostly in rarely used functionality and from stricter error handling.

Contributors

Name
Kornel Lesiński
Peter Lyons
Hunter Loftis
Nick Baugh

License

MIT © TJ Holowaychuk

superagent (forwardemail/superagent)

Searching Database…

Что это такое?Superagent — это небольшая прогрессивная библиотека для HTTP-запросов с одинаковым API в браузере и в Node.js, поддерживающая многие высокоуровневые возможности HTTP-клиента.
Это для браузера или для Node.js?И для того, и для другого — она изоморфная. Один API работает и в Node, и в браузере, где готовая сборка весит всего 50 КБ после минификации и gzip-сжатия и раздаётся через jsdelivr, unpkg или папку dist пакета.
Как добавить её в свой проект?Установите её через npm или yarn (npm install superagent). В браузере можно обойтись без сборщика: подключите готовый минифицированный файл с CDN или из папки dist пакета.
Нужна ли какая-то определённая версия Node?Node.js 14.18.0 или новее — согласно заявленному полю engines. На стороне браузера ничего не нужно, кроме тега script или импорта через сборщик.
На что обратить внимание при обновлении со старой версии?Главная сложность — само обновление: критические изменения сосредоточены в редко используемой функциональности и в более строгой обработке ошибок, поэтому сверяйтесь с changelog в GitHub releases между версиями.
Будет ли работать в мобильных браузерах или только на компьютере?Работает и там, и там. Поддерживаются свежие версии Chrome, Firefox, Edge, Opera и Safari, а также iOS Safari, Android Chrome, Samsung Internet, мобильные QQ и UC и KaiOS 2.5.
Как сделать запрос с параметрами query?Через цепочку: superagent.get('/some-url').query({ action: 'edit', city: 'London' }).end((err, res) => { ... }) — та же текучая цепочка принимает и плагины через .use().
Там есть система плагинов?Да — плагины подключаются к отдельному запросу через .use(). В экосистеме есть плагины для кеширования, троттлинга, мокирования, префиксов URL, работы с кодировками, парсинга через cheerio (res.$) и подписи AWS-запросов; имена плагинов принято начинать с superagent-.
Superagent до сих пор активно поддерживается?Да. Его поддерживают для Forward Email и Lad — команды @forwardemail и @ladjs, вместе с @spamscanner, @breejs, @cabinjs и @lassjs; проект существует с 2011 года, а changelog публикуются в GitHub releases.
Size
7 MB
Stars
16.6K
Age
15y
Commits · 90 Days