What is superagent?
The superagent npm package is a small progressive client-side HTTP request library, and Node.js module with the same API, sporting many high-level HTTP client features. It is designed to make HTTP requests from both Node.js and browsers.
What are superagent's main functionalities?
GET requests
This feature allows you to make GET requests to retrieve data from a server. You can include query parameters and handle the response asynchronously.
superagent.get('/search').query({ query: 'Manny' }).end(function(err, res){ /* handling response */ });
POST requests
This feature is used to send POST requests to a server. You can send data as part of the request body and set custom headers.
superagent.post('/api/pets').send({ name: 'Manny', species: 'cat' }).set('X-API-Key', 'foobar').end(function(err, res){ /* handling response */ });
Handling responses
This feature allows you to handle responses from the server, checking if the request was successful and then acting on the data received.
superagent.get('/some-url').end(function(err, res){ if (res.ok) { console.log('yay got ' + JSON.stringify(res.body)); } else { console.log('Oh no! error ' + res.text); } });
Promises and async/await
Superagent can be used with promises and async/await syntax for better asynchronous control flow.
async function getData() { try { const res = await superagent.get('/some-url'); console.log(res.body); } catch (err) { console.error(err); } }
Pipelining requests
This feature allows you to pipe the response stream directly to a file or another writable stream.
superagent.get('/some-url').pipe(fs.createWriteStream('result.txt'))
Other packages similar to superagent
axios
Axios is a promise-based HTTP client for the browser and Node.js. It provides a simple API and handles requests and responses in JSON format. Compared to superagent, it has built-in CSRF protection and supports interceptors for request and response transformation.
fetch
The Fetch API provides a more modern alternative to XMLHttpRequest for making HTTP requests in the browser. It is not an npm package but a built-in browser API. It returns promises and works with async/await. Unlike superagent, it is not Node.js compatible without polyfills.
got
Got is a Node.js HTTP request library that is designed to be a simpler and more user-friendly alternative to Node's native 'http' module. It supports promises and async/await, streams, and advanced features like retries and timeouts. It is often compared to superagent for its simplicity and feature set.
node-fetch
node-fetch is a light-weight module that brings the browser Fetch API to Node.js. It is similar to superagent but is designed to mimic the Fetch API as closely as possible. It is promise-based and supports stream consumption.
request
Request is a simplified HTTP request client for Node.js, but it has been deprecated. It was known for its simplicity and wide adoption. Superagent offers a similar feature set but continues to be maintained and updated.
SuperAgent
SuperAgent is a small progressive client-side HTTP request library, and Node.js module with the same API, sporting many high-level HTTP client features. View the docs.
Motivation
This library spawned from my frustration with jQuery's weak & inconsistent Ajax support. jQuery's API while having recently added some promise-like support, is largely static, forcing you to build up big objects containing all the header fields and options, not to mention most of the options are awkwardly named "type" instead of "method", etc. Onto examples!
The following is what you might typically do for a simple GET with jQuery:
$.get('/user/1', function(data, textStatus, xhr){
});
great, it's ok, but it's kinda lame having 3 arguments just to access something on the xhr
. Our equivalent would be:
request.get('/user/1', function(res){
});
the response object is an instanceof request.Response
, encapsulating all of this information instead of throwing a bunch of arguments at you. For example we can check res.status
, res.header
for header fields, res.text
, res.body
etc.
An example of a JSON POST with jQuery typically might use $.post()
, however once you need to start defining header fields you have to then re-write it using $.ajax()
... so that might look like:
$.ajax({
url: '/api/pet',
type: 'POST',
data: { name: 'Manny', species: 'cat' },
headers: { 'X-API-Key': 'foobar' }
}).success(function(res){
}).error(function(){
});
Not only is it ugly it's pretty opinionated, jQuery likes to special-case {4,5}xx, for example you cannot (easily at least) receive a parsed JSON response for say "400 Bad Request". This same request would look like this:
request
.post('/api/pet')
.send({ name: 'Manny', species: 'cat' })
.set('X-API-Key', 'foobar')
.set('Accept', 'application/json')
.end(function(error, res){
});
building on the existing API internally we also provide something similar to $.post()
for those times in life where your interactions are very basic:
request.post('/api/pet', cat, function(error, res){
});
Running node tests
Install dependencies:
$ npm install
Run em!
$ make test
Running browser tests
Install the test server deps (nodejs / express):
$ npm install
Start the test server:
$ make test-server
Visit localhost:4000/
in the browser.
Browser build
The browser build of superagent is located in ./superagent.js
Examples:
Wiki
For superagent extensions such as couchdb and oauth visit the wiki.
License
MIT