[typescript] Superagent를 사용하여 HTTP 요청 보내기

이 블로그 포스트에서는 TypeScript에서 Superagent를 사용하여 HTTP 요청을 보내는 방법에 대해 알아보겠습니다.

Superagent란 무엇인가요?

Superagent는 Node.js 및 브라우저용으로 제공되는 AJAX 및 HTTP 클라이언트 라이브러리입니다. 이 라이브러리를 사용하면 프론트엔드 및 백엔드에서 HTTP 요청을 쉽게 보낼 수 있습니다.

Superagent 설치

먼저 프로젝트 디렉토리에서 Superagent를 설치해야 합니다. 아래 명령을 사용하여 Superagent를 설치합니다.

npm install superagent

TypeScript에서 Superagent 사용하기

TypeScript에서 Superagent를 사용하려면 @types/superagent를 설치하여 타입 선언을 가져와야 합니다.

npm install @types/superagent

이제 Superagent를 사용하여 HTTP GET 요청을 보내는 간단한 예제를 살펴보겠습니다.

import * as superagent from 'superagent';

superagent
  .get('https://api.example.com/data')
  .end((err, res) => {
    if (!err && res) {
      console.log(res.body);
    } else {
      console.error(err);
    }
  });

위 코드에서 우리는 superagent.get()을 사용하여 https://api.example.com/data로 GET 요청을 보내고, 응답을 처리하는 콜백 함수를 정의했습니다.

요청 파라미터와 헤더 추가

Superagent를 사용하여 요청 파라미터나 헤더를 추가하는 것 또한 간단합니다. 아래 예제에서는 쿼리 문자열과 헤더를 추가하는 방법을 보여줍니다.

superagent
  .get('https://api.example.com/data')
  .query({ page: 2, limit: 10 })
  .set('Authorization', 'Bearer YOUR_ACCESS_TOKEN')
  .end((err, res) => {
    if (!err && res) {
      console.log(res.body);
    } else {
      console.error(err);
    }
  });

위 코드에서는 query()를 사용하여 쿼리 문자열을 추가하고, set()을 사용하여 인증 헤더를 추가했습니다.

마무리

이제 TypeScript에서 Superagent를 사용하여 HTTP 요청을 보내는 방법을 알아보았습니다. Superagent를 사용하면 간편하게 HTTP 요청을 보낼 수 있으며, 유연하고 확장 가능한 기능을 제공합니다.

더 많은 정보를 원하시면 Superagent 공식 문서를 참고하세요.