superagent

repository·master·Indexed 12 days ago

https://github.com/forwardemail/superagent

An elegant and feature-rich HTTP request library for Node.js (v14.18.0+) and the browser. It provides a fluent API supporting automatic JSON parsing, plugins, and multiple asynchronous patterns including promises and async/await. Key features include support for Unix Domain Sockets, HTTP/2, multipart/form-data via .attach() and .field(), and streaming via .pipe() in Node.js. Version 10.3.0.

Tokens
18.6K
Snippets
76
Records
84
Agent score
89%

What's inside superagent

  1. Install and use SuperAgent

    master

    SuperAgent is a lightweight Ajax API designed for flexibility, readability, and low learning curve. It works in both the browser and Node.js environments. You can initiate a request by calling methods on the request object and then sending it using .then(), .end(), or await.

    request
      .post('/api/pet')
      .send({ name: 'Manny', species: 'cat' })
      .set('X-API-Key', 'foobar')
      .set('Accept', 'application/json')
      .then((res) => {
        alert('yay got ' + JSON.stringify(res.body));
      });
  2. Choose between Browser and Node.js implementations

    master

    SuperAgent provides two distinct implementations:

    1. Browser version: Uses XHR.
    2. Node.js version: Uses the core http module.

    Environment Selection

    • Webpack/Browserify: These tools will automatically select the browser version by default.
    • Webpack for Node.js: You must explicitly set the target to node in your Webpack configuration.
    • Electron: To use the browser version (so requests appear in Chrome DevTools) instead of the Node version, use require('superagent/superagent').
  3. Use SuperAgent Agents for stateful requests (Cookies)

    master

    In Node.js, SuperAgent does not store cookies by default. To maintain state (like a session) across multiple requests, use request.agent() to create an agent instance. Each agent has its own independent cookie jar.

    const agent = request.agent();
    agent.post('/login').then(() => {
      return agent.get('/cookied-page');
    });
  4. Use SuperAgent with Promises and async/await

    master

    SuperAgent requests are "thenable" and fully compatible with JavaScript Promises and async/await syntax.

    Important: If you use .then() or await, do not call .end() or .pipe(). Using these methods together will disable the request functionality.

    // Using async/await
    const res = await request.get(url);
    
    // Using generators (e.g., with co)
    const req = request.get('http://local').auth('tobi', 'learnboost');
    const res = yield req;
  5. Handle multipart/form-data responses

    master

    In Node.js, SuperAgent uses Formidable to support multipart/form-data. When a response is multipart, you can access files via res.files and text fields via res.body.

    Example structure:

    • res.body.name contains text fields.
    • res.files.image contains a File object with properties like path, filename, etc.
  6. Handle multipart/form-data responses in Node.js

    master

    The Node.js client uses the formidable module to handle multipart/form-data. When a multipart response is parsed, you can access:

    • res.body: Contains standard form fields (e.g., res.body.name).
    • res.files: Contains file objects (e.g., res.files.image) which include the path on disk, filename, and other metadata.
  7. Handle errors and HTTP status codes

    master

    SuperAgent treats 4xx and 5xx responses (and unhandled 3xx responses) as errors by default.

    Error Object Properties

    When an HTTP error occurs, the error object contains:

    • err.status: The HTTP status code (e.g., 404).
    • err.response: An object containing all response properties.

    Note: Network failures or timeouts do not contain err.status or err.response.

    Customizing Error Logic with .ok()

    If you want to treat certain status codes as successful (e.g., treating a 404 as a valid response), use the .ok(callback) method. The callback receives the response and should return true if the response should be considered a success.

    // Checking status manually
    if (err && err.status === 404) {
      alert('oh no ' + res.body.message);
    }
    
    // Using .ok() to redefine success
    request.get('/404')
      .ok(res => res.status < 500)
      .then(response => {
        // 404 is now treated as a successful response
      })
  8. Handle JSON and URL-encoded response bodies

    master

    For application/json and application/x-www-form-urlencoded responses, the parsed object is available at res.body.

    • Nesting: Only supports one level of nesting (e.g., res.body.user.name). For complex structures, use JSON.
    • Arrays: To send arrays via URL-encoded forms, repeat the key: .send({color: ['red','blue']}) results in color=red&color=blue. SuperAgent does not automatically add [] to keys; you must include them manually if the server requires them (e.g., .field('friends[]', ['loki', 'jane'])).
  9. Use Agents to manage cookies and default options

    master

    An Agent is a persistent instance of SuperAgent that can maintain state.

    • Cookie Persistence (Node.js): In Node, SuperAgent does not save cookies by default. Use request.agent() to create an agent that maintains a separate cookie jar for all requests made through it.
    • Browser Behavior: In the browser, cookies are managed by the browser itself, so .agent() does not provide isolation.
    • Default Options: Any configuration applied to an agent (via use, auth, set, query, etc.) will be applied to every request made by that agent.

    Supported configuration methods on Agents: use, on, once, set, query, type, accept, auth, withCredentials, sortQuery, retry, ok, redirects, timeout, buffer, serialize, parse, ca, key, pfx, cert.

    const agent = request.agent();
    agent
      .post('/login')
      .then(() => {
        return agent.get('/cookied-page');
      });
  10. Handle HTTP errors and status codes

    master

    SuperAgent considers 4xx and 5xx responses (and unhandled 3xx responses) as errors by default.

    Error Object Properties

    When an error occurs, the error object contains:

    • err.status: The HTTP status code (e.g., 404, 500).
    • err.response: The full response object.

    Customizing Error Logic

    If you want to treat certain error status codes as successful responses, use the .ok(callback) method. The callback receives the response and should return true if it should be treated as a success.

    Handling Errors in Callbacks

    Callbacks receive two arguments: (error, response). If no error occurred, the first argument is null.

    // Customizing what is considered an 'ok' response
    request.get('/404')
      .ok(res => res.status < 500)
      .then(response => {
        // 404 is now treated as a successful response
      });
    
    // Checking specific error status
    if (err && err.status === 404) {
      alert('oh no ' + res.body.message);
    }
  11. Make basic HTTP requests with SuperAgent

    master

    You can initiate requests using method names on the request object (e.g., .get(), .post(), .put(), .del(), .head(), .patch()) or by passing the method as a string to request(). Requests can be sent using Promises (.then(), .catch()), the .end() callback (not recommended), or await.

    Common HTTP Methods:

    • GET (default)
    • POST
    • PUT
    • DELETE (use .del() for IE compatibility)
    • HEAD
    • PATCH

    Response and Error handling:

    • Success response: res.body, res.headers, res.status
    • Error response: err.message, err.response
    // Using Promise/await
    request
      .get('/search')
      .then(res => {
         console.log(res.body, res.headers, res.status);
      })
      .catch(err => {
         console.log(err.message, err.response);
      });
    
    // Using string method
    request('GET', '/search').then(success, failure);
    
    // Using callback (not recommended)
    request('GET', '/search').end(function(err, res){
      if (res.ok) {}
    });
  12. Use superagent in Node.js

    master

    In Node.js, you can use superagent with callbacks, promises (.then/.catch), or async/await.

    Common methods include:

    • .post(url): Initiates a POST request.
    • .send(data): Sends a JSON post body.
    • .set(name, value): Sets HTTP request headers.
    • .end(callback): Sends the request and executes a callback (for the callback pattern).
    • .query(data): Adds query string parameters to the request.
    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);
      }
    })();