[Node.js] HTTP 요청 관련 라이브러리들(request vs axios vs superagent)
서론
우연히 쓸 일이 생겨서, HTTP Request 라이브러리들을 정리해보았다.
개인적으로는 가벼움 때문에 superagent를 사용하였으며,
사실상 request와 거의 똑같이 쓸 수 있는 구조로 되어 있어 편리하게 사용하였다.
1. request
공식 문서 : https://github.com/request/request
request/request
🏊🏾 Simplified HTTP request client. Contribute to request/request development by creating an account on GitHub.
github.com
상당히 다양한 HTTP request 형식을 지원하고 있고, npm 초창기부터 있던 모듈이다.
2020년 2월 11일 이후로 deprecated 되었다고 한다!
단점
- promise 기반이 아니다. (이게 제일 큰 단점이다.)
- deprecated되었다.
예제
request
.get('http://google.com/img.png')
.on('response', function(response) {
console.log(response.statusCode) // 200
console.log(response.headers['content-type']) // 'image/png'
})
.pipe(request.put('http://mysite.com/img.png'))
2. axios
공식 문서 : https://github.com/axios/axios
axios/axios
Promise based HTTP client for the browser and node.js - axios/axios
github.com
장점
- 대부분의 브라우저를 지원한다. (구형 브라우저 및 최신 브라우저까지)
- JSON 데이터를 자동으로 변환해준다.
- 다양한 기능들이 있다(요청을 중간에 취소한다거나, 응답시간 초과 시 어떤 동작을 하게 한다거나)
- 가독성이 좋게 구성되어 있다.
- Promise 기반이다.
- 많은 사람들이 사용하고 있다!
단점
- 다양한 기능들만큼 좀 무겁다.
예제
const axios = require('axios');
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
3. superagent
공식 문서 : https://visionmedia.github.io/superagent/
SuperAgent — elegant API for AJAX in Node and browsers
SuperAgent SuperAgent is light-weight progressive ajax API crafted for flexibility, readability, and a low learning curve after being frustrated with many of the existing request APIs. It also works with Node.js! request .post('/api/pet') .send({ name: 'Ma
visionmedia.github.io
장점
- 경량으로 만들어져 있다! (축소된 버전의 superagent는 6KB라고 한다)
- 최신 브라우저에서 모두 작동한다고 한다.
- Promise 기반이다.
- Plugin 생태계가 있다고 한다.(superagent-cache 등의 플러그인이 있는 것으로 보인다.)
단점
아직 많은 유저들이 쓰고 있는 거 같지는 않다.
예제
request
.post('/api/pet')
.send({ name: 'Manny', species: 'cat' })
.set('X-API-Key', 'foobar')
.set('Accept', 'application/json')
.then(res => {
alert('yay got ' + JSON.stringify(res.body));
});