Superagent는 브라우저 및 Node.js를 위한 점진적이고 가벼운 HTTP 요청 클라이언트 라이브러리입니다.
요청 전송
GET 요청
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 및 Async/Await 스타일
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 요청 및 JSON 페이로드
superagent
.post('/api/items')
.send({ item: 'Widget', qty: 10 })
.set('X-API-Key', 'secret')
.then(res => console.log(res.body))
멀티파트 폼 및 파일 업로드
superagent
.post('/upload')
.field('title', 'Profile Picture')
.attach('avatar', 'path/to/avatar.png')
.then(res => console.log('Uploaded!'))
응답 객체 속성
| 속성 | 타입 | 설명 |
|---|---|---|
res.body |
Object |
파싱된 응답 본문 (JSON / Form) |
res.text |
String |
파싱되지 않은 원시 응답 텍스트 |
res.status |
Number |
HTTP 상태 코드 (예: 200, 404) |
res.header |
Object |
응답 헤더 해시 |
res.ok |
Boolean |
상태 코드가 2xx이면 true |
res.clientError |
Boolean |
상태 코드가 4xx이면 true |
res.serverError |
Boolean |
상태 코드가 5xx이면 true |
res.type |
String |
매개변수를 제외한 Content-Type |