Superagent هي مكتبة خفيفة ومرنة لتنفيذ طلبات HTTP التدريجية في جانب العميل ونظام Node.js.
إجراء الطلبات (Making Requests)
طلب 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)
})
صيغة الوعود و 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))
نماذج Multipart ورفع الملفات
superagent
.post('/upload')
.field('title', 'Profile Picture')
.attach('avatar', 'path/to/avatar.png')
.then(res => console.log('Uploaded!'))
خصائص كائن الاستجابة (Response Object)
| الخاصية | النوع | الوصف |
|---|---|---|
res.body |
Object |
جسم الاستجابة المحلل (JSON / Form) |
res.text |
String |
النص الخام غير المحلل للاستجابة |
res.status |
Number |
رمز حالة HTTP (مثل 200 أو 404) |
res.header |
Object |
جدول ترويسات الاستجابة |
res.ok |
Boolean |
صحيح true إذا كانت الحالة 2xx |
res.clientError |
Boolean |
صحيح true إذا كانت الحالة 4xx |
res.serverError |
Boolean |
صحيح true إذا كانت الحالة 5xx |
res.type |
String |
نوع المحتوى Content-Type بدون معلمات |