Superagent is a progressive, lightweight client-side HTTP request library and Node.js module.
Making Requests
GET Request
const superagent = require('superagent')
superagent
.get('/api/users')
.query({ role: 'admin', page: 2 })
.set('Accept', 'application/json')
.end((err, res) => {
if (err) return console.error(err)
console.log(res.status)
console.log(res.body)
})
Promise and Async/Await Style
try {
const res = await superagent
.post('/api/users')
.send({ name: 'John Doe', email: '[email protected]' })
.set('Authorization', 'Bearer token123')
console.log(res.body)
} catch (err) {
console.error(err.response ? err.response.body : err.message)
}
POST Requests and JSON Payloads
superagent
.post('/api/items')
.send({ item: 'Widget', qty: 10 })
.set('X-API-Key', 'secret')
.then(res => console.log(res.body))
Multipart Form / File Uploads
superagent
.post('/upload')
.field('title', 'Profile Picture')
.attach('avatar', 'path/to/avatar.png')
.then(res => console.log('Uploaded!'))
Response Object Properties
| Property | Type | Description |
|---|---|---|
res.body |
Object |
Parsed response body (JSON / Form) |
res.text |
String |
Raw unparsed response text |
res.status |
Number |
HTTP status code (e.g. 200, 404) |
res.header |
Object |
Response headers hash |
res.ok |
Boolean |
True if status is 2xx |
res.clientError |
Boolean |
True if status is 4xx |
res.serverError |
Boolean |
True if status is 5xx |
res.type |
String |
Content-Type without parameters |