[nodejs] 비동기식 RESTful API 호출
Node.js는 JavaScript를 사용하는 데에 특화된 서버 측 런타임 환경으로, 이를 이용해 간단하게 비동기식 RESTful API 호출을 구현할 수 있습니다.
HTTP 모듈을 사용한 API 호출
Node.js의 내장 HTTP 모듈을 사용하여 RESTful API를 호출할 수 있습니다. 아래는 HTTP 모듈을 사용한 API 호출의 예시입니다.
const http = require('http');
const options = {
host: 'api.example.com',
path: '/endpoint',
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
};
const req = http.request(options, res => {
let data = '';
res.on('data', chunk => {
data += chunk;
});
res.on('end', () => {
console.log(JSON.parse(data));
});
});
req.on('error', error => {
console.error(error);
});
req.end();
Axios 모듈을 사용한 API 호출
Axios는 HTTP 클라이언트 라이브러리로, Node.js 환경에서의 API 호출을 위해 많이 사용됩니다. 아래는 Axios 모듈을 사용한 API 호출의 예시입니다.
const axios = require('axios');
axios.get('https://api.example.com/endpoint')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
Axios를 사용하면 간단하게 API 호출 및 응답을 처리할 수 있으며, 에러 핸들링도 쉽게 구현할 수 있습니다.
Node.js를 사용하여 RESTful API 호출 시, HTTP 모듈 또는 Axios를 사용하여 비동기적으로 API를 호출할 수 있습니다. 또한, 각각의 방법에 따라 API 호출 및 응답 데이터를 처리하는 방법이 다르므로, 상황에 맞게 선택하여 사용할 수 있습니다.
참고 자료
- Node.js 공식 문서: Node.js 공식 문서
- Axios GitHub 저장소: Axios GitHub 저장소 ```