Superagent Parsing Typed HTTP Responses
Use Superagent to GET and POST with automatic parsing, retries, timeout control, and typed response body access for JSON and form payloads.
Code
import superagent from 'superagent';
const agent = superagent.agent();
const profile = await agent
.get('https://api.example.com/profile')
.set('Authorization', 'Bearer demo-token')
.query({ fields: 'name,email' })
.timeout({ response: 4000, deadline: 9000 })
.retry(2, (err, res) => !!err || res.status >= 500);
console.log('profile name:', profile.body.name);
const created = await agent
.post('https://api.example.com/orders')
.type('json')
.send({ sku: 'A-1', quantity: 3 })
.on('error', (err) => console.error('submit failed:', err.message));
console.log('created order id:', created.body.id);
const form = await agent
.post('https://api.example.com/feedback')
.type('form')
.send({ rating: 5, comment: 'great' });
console.log('form status:', form.status);How it works
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
Everything operates on top-level bindings: agent, profile, created, form.
Emits through the .error level methods with structured payloads, so downstream transports can route by level and field.
What to watch for
- External dependency:
superagent— install it before running the snippet.
Putting it to use
Output lines are prefixed (profile name:, submit failed:, created order id:), making each step’s effect easy to spot.
Core lines
.retry(2, (err, res) => !!err || res.status >= 500);
const created = await agent
.post('https://api.example.com/orders')
.type('json')
.send({ sku: 'A-1', quantity: 3 })
.on('error', (err) => console.error('submit failed:', err.message));
const form = await agent
.post('https://api.example.com/feedback')
.type('form')
.send({ rating: 5, comment: 'great' });
Interactive Tools for This Topic
Accept Header ParserParse an Accept header into media ranges with their quality values and specificity, sorted by preference for content negotiation debugging.Basic & Bearer Auth Header ToolEncode and decode HTTP Authorization Basic and Bearer headers locally with UTF-8 Base64 validation and automatic JWT claim and expiry inspection.Set-Cookie ParserParse one or more Set-Cookie header values into the cookie name, value, and attributes like Path, Domain, Expires, Max-Age, Secure, HttpOnly, and SameSite.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.
FAQ
- Are there third-party dependencies?
- `superagent` — install it with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.