クイックリファレンス

Superagent チートシート

JavaScript 向け HTTP クライアントライブラリ Superagent のクイックリファレンス:GET/POST リクエスト、ヘッダー、クエリ文字列、レスポンスプロパティの解説。

· 公開日

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

関連テーマ