[typescript] Superagent를 이용한 JSON 데이터 전송 및 수신

이번 글에서는 Superagent 라이브러리를 사용하여 TypeScript로 JSON 데이터를 전송하고 수신하는 방법에 대해 알아보겠습니다. Superagent는 HTTP 클라이언트 라이브러리로, 서버와의 통신을 쉽게 처리할 수 있습니다.

Superagent 설치

먼저, Superagent 라이브러리부터 설치해야 합니다. 아래의 명령어를 사용하여 npm을 통해 라이브러리를 설치할 수 있습니다.

npm install superagent

TypeScript에서 Superagent 사용하기

이제 TypeScript 프로젝트에서 Superagent를 사용해보겠습니다. 아래는 간단한 예제 코드입니다.

import * as superagent from 'superagent';

const apiUrl = 'https://api.example.com/data';

// 데이터 전송
superagent
  .post(apiUrl)
  .send({ key: 'value' })
  .set('Accept', 'application/json')
  .end((err, res) => {
    if (err || !res.ok) {
      console.error('Error occurred');
    } else {
      console.log('Data sent successfully');
    }
  });

// 데이터 수신
superagent
  .get(apiUrl)
  .set('Accept', 'application/json')
  .end((err, res) => {
    if (err || !res.ok) {
      console.error('Error occurred');
    } else {
      console.log('Received data:', res.body);
    }
  });

위 코드에서 superagent.postsuperagent.get를 사용하여 각각 POST 및 GET 요청을 보냅니다. send 메서드를 사용하여 전송할 데이터를 설정하고, end 메서드 내에서 결과를 처리합니다.

결론

이제 Superagent를 사용하여 TypeScript에서 JSON 데이터를 전송하고 수신하는 방법에 대해 알아보았습니다. 이를 통해 서버와의 효율적인 통신을 쉽게 구현할 수 있습니다.

더 많은 정보는 Superagent 공식 문서에서 확인할 수 있습니다.

Happy coding!