Szybka pomoc

Ściągawka z Superagent

Szybki przewodnik po bibliotece klienta HTTP Superagent w JavaScript: żądania GET i POST, nagłówki, parametry zapytań i właściwości odpowiedzi.

· Opublikowano

Superagent to lekka i elastyczna biblioteka żądań HTTP dla przeglądarek i środowiska Node.js.

Wykonywanie żądań

Żądanie 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)
  })

Styl z Promise i 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)
}

Żądania POST i dane JSON

superagent
  .post('/api/items')
  .send({ item: 'Widget', qty: 10 })
  .set('X-API-Key', 'secret')
  .then(res => console.log(res.body))

Formularze Multipart i przesyłanie plików

superagent
  .post('/upload')
  .field('title', 'Profile Picture')
  .attach('avatar', 'path/to/avatar.png')
  .then(res => console.log('Uploaded!'))

Właściwości obiektu odpowiedzi

Właściwość Typ Opis
res.body Object Przetworzona treść odpowiedzi (JSON / Formularz)
res.text String Surowy tekst odpowiedzi
res.status Number Kod statusu HTTP (np. 200, 404)
res.header Object Nagłówki odpowiedzi
res.ok Boolean True jeśli status to 2xx
res.clientError Boolean True jeśli status to 4xx
res.serverError Boolean True jeśli status to 5xx
res.type String Content-Type bez parametrów

Powiązane tematy