SuperAgent是一個輕量級的HTTP客戶端,使用Node.js內置的HTTP模塊,可以在客戶端或伺服器端使用,支持promise,鏈式寫法,可將請求結果自定義解析為JSON格式,支持Cookie,動態URL參數等,是一個非常全能的HTTP客戶端工具。
一、安裝和使用
SuperAgent是一個npm包,可以使用npm命令進行安裝。
npm install superagent --save
安裝後,在項目中引入SuperAgent。
const request = require('superagent');
使用SuperAgent發送一個GET請求,需要輸入請求的URL,並在end回調函數中處理響應結果。
request.get('/api/user')
.end((err, res) => {
if (err) throw err;
console.log(res.body);
});
二、發送HTTP請求
1. 基本用法
SuperAgent支持HTTP/HTTPS協議,支持GET/POST/PUT/DELETE等請求方法,可以通過chainable語法構造請求,如下所示:
request
.post('/api/user')
.send({ name: 'John', email: 'john@example.com' })
.set('X-API-Key', 'foobar')
.set('Accept', 'application/json')
.end((err, res) => {
if (err) throw err;
console.log(res.body);
});
請求中採用鏈式調用,用.send()設置請求體,用.set()設置請求頭,用.end()結束請求,用於回調響應內容。
2. 設置請求頭和請求體
在實際應用中,有時需要在請求中設置請求頭和請求體,SuperAgent提供了.set()和.send()方法分別設置請求頭和請求體,如下所示:
request.post('/api/user')
.set('Content-Type', 'application/json')
.set('X-API-Key', 'foobar')
.send({ name: 'John', email: 'john@example.com' })
.end((err, res) => {
if (err) throw err;
console.log(res.body);
});
以上代碼,通過.set()方法設置了Content-Type和X-API-Key兩個請求頭,通過.send()方法設置請求體。
3. 發送表單數據
發送表單數據時,需要設置Content-Type為application/x-www-form-urlencoded,以便服務端能夠正確解析請求。SuperAgent提供了.type()方法用於設置Content-Type,並通過.send()方法發送表單數據,如下所示:
request.post('/api/user')
.type('form')
.send({ name: 'John', email: 'john@example.com' })
.end((err, res) => {
if (err) throw err;
console.log(res.body);
});
4. 發送文件
發送文件時需要通過.formData()方法來添加文件,如下所示:
request.post('/api/upload')
.attach('avatar', '/path/to/avatar.jpg')
.end((err, res) => {
if (err) throw err;
console.log(res.body);
});
以上代碼使用SuperAgent發送一個POST請求,添加了一個名為avatar,路徑為/path/to/avatar.jpg的文件,使用.attach()方法添加文件。
三、處理響應數據
SuperAgent支持promise,支持鏈式調用,通過.then()方法處理響應結果,也可以在.end()回調函數中處理,如下所示:
request.get('/api/user')
.then(res => {
console.log(res.body);
})
.catch(err => {
console.error(err);
});
以上代碼使用SuperAgent發送一個GET請求,處理響應結果並通過.then()方法輸出響應內容,通過.catch()方法捕獲錯誤信息。
1. 解析響應數據為JSON/XML格式
SuperAgent默認將響應結果解析為JSON格式,如果響應數據不是JSON格式需要手動指定解析格式,如下所示:
request.get('/api/data.xml')
.set('Accept', 'application/xml')
.buffer(true)
.parse((res, callback) => {
res.text = '';
res.setEncoding('utf8');
res.on('data', chunk => {
res.text += chunk;
});
res.on('end', () => {
callback(null, res.text);
});
})
.end((err, res) => {
if (err) throw err;
console.log(res.text);
});
以上代碼設置了Accept請求頭,表示需要響應數據為XML格式,並使用.parse()方法自定義響應的解析邏輯。
2. Cookies
在處理HTTP請求時,SuperAgent能夠處理客戶端的Cookies和服務端的Cookies,通過Cookies實現狀態保持。可以使用.set()方法設置請求頭中的Cookie欄位,如下所示:
request.get('/api/user')
.set('Cookie', 'sessionid=123456')
.end((err, res) => {
if (err) throw err;
console.log(res.body);
});
以上代碼使用SuperAgent發送一個GET請求,設置了請求頭中的Cookie欄位。
3. 響應攔截器
SuperAgent支持響應攔截器,可以在響應結果返回後在.then()方法中執行,如下所示:
request.get('/api/user')
.then(res => {
console.log(res.body);
return res.body.id;
})
.then(id => {
return request.post('/api/user/' + id)
.send({ status: 'online' });
})
.then(res => {
console.log(res.body);
})
.catch(err => {
console.error(err);
});
以上代碼發送一個GET請求,拿到響應結果後,再通過.then()方法處理響應內容並返回id,然後拼接請求URL發送一個POST請求,同時傳遞status參數。
四、超時處理
在實際應用中,保持網路正常運行是非常困難的。SuperAgent提供了.timeout()方法來設置請求超時時間,可以在調用的地方設置超時時間(單位:毫秒),如下所示:
request.get('/api/user')
.timeout(5000)
.end((err, res) => {
if (err && err.timeout) {
console.error('請求超時');
} else if (err) {
console.error(err);
} else {
console.log(res.body);
}
});
以上代碼設置了請求超時時間為5秒,如果超時了,則拋出超時錯誤。
五、總結
SuperAgent是一個非常強大的HTTP客戶端,支持Node.js內置的HTTP模塊,支持promise,鏈式寫法,可自定義解析結果為JSON格式,支持Cookie,動態URL參數等功能。在實際應用中,使用SuperAgent可以輕鬆處理HTTP請求和響應,將開發效率大大提高。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/301067.html