Got를 사용하여 Node.js에서 HTTP 요청 만들기

WBOY
풀어 주다: 2024-08-28 06:06:02
원래의
400명이 탐색했습니다.

Node.js에서 애플리케이션을 구축할 때 외부 API와 상호작용하든, 데이터를 가져오든, 서비스 간 통신을 하든 HTTP 요청을 만드는 것은 기본적인 작업입니다. Node.js에는 요청을 위한 내장 http 모듈이 있지만 가장 사용자 친화적이거나 기능이 풍부한 솔루션은 아닙니다. Got와 같은 도서관이 여기에 속합니다.

Got은 가볍고 기능이 풍부한 Node.js용 약속 기반 HTTP 클라이언트입니다. 이는 HTTP 요청 프로세스를 단순화하고 깨끗한 API, 자동 재시도, 스트림 지원 등을 제공합니다. 이 기사에서는 Got를 사용하여 HTTP 요청을 생성하고 오류를 처리하는 방법을 살펴보겠습니다.

HTTP 요청에 대해 Got를 선택하는 이유는 무엇입니까?

코드를 살펴보기 전에 많은 개발자가 Got를 선호하는 이유를 이해하는 것이 중요합니다.

  • 간단한 API: Got는 다양한 유형의 HTTP 요청을 쉽게 수행할 수 있는 깔끔하고 직관적인 API를 제공합니다.
  • Promise 기반: Got는 완전한 Promise 기반이므로 더 깔끔하고 읽기 쉬운 코드를 위해 async/await 구문을 사용할 수 있습니다.
  • 자동 재시도: Got는 네트워크 오류나 기타 문제에 대한 요청을 자동으로 재시도할 수 있으며 이는 애플리케이션의 안정성을 향상시키는 데 특히 유용합니다.
  • 스트림 지원: Got는 스트리밍을 지원하므로 대용량 파일을 다운로드하거나 데이터를 덩어리로 작업하는 데 유용합니다.
  • 사용자 정의 가능: Got는 헤더, 쿼리 매개변수, 시간 초과 등을 수정하는 옵션을 포함하여 고도로 사용자 정의가 가능합니다.

설치 중

Got을 시작하려면 먼저 Node.js 프로젝트에 설치해야 합니다. 아직 Node.js 프로젝트를 설정하지 않았다면 다음 단계를 따르세요.

  1. 프로젝트 초기화: 터미널을 열고 프로젝트를 위한 새 디렉터리를 만듭니다.
   mkdir got-http-requests
   cd got-http-requests
   npm init -y
로그인 후 복사

이 명령은 새 프로젝트 디렉터리를 생성하고 package.json 파일로 초기화합니다.

  1. Got 설치: 다음으로 npm을 사용하여 Got를 설치합니다.
   npm install got
로그인 후 복사

이제 프로젝트에 Got가 추가되었으며 이를 사용하여 HTTP 요청을 할 수 있습니다.

Got를 사용하여 HTTP 요청 만들기

Got을 사용하면 다양한 유형의 HTTP 요청을 쉽게 수행할 수 있습니다. 몇 가지 일반적인 사용 사례를 살펴보겠습니다.

1. 기본 GET 요청 만들기

GET 요청은 가장 일반적인 유형의 HTTP 요청으로, 일반적으로 서버에서 데이터를 검색하는 데 사용됩니다. Got를 사용하면 GET 요청을 만드는 것이 간단합니다.

const got = require('got');

(async () => {
    try {
        const response = await got('https://jsonplaceholder.typicode.com/posts/1');
        console.log('GET Request:');
        console.log(response.body);
    } catch (error) {
        console.error('Error in GET request:', error.message);
    }
})();
로그인 후 복사
  • 설명:
  • 엔드포인트: https://jsonplaceholder.typicode.com/posts/1은 ID가 1인 게시물의 세부정보를 반환하는 테스트 API입니다.
  • Got 구문: got(url) 함수는 지정된 URL로 GET 요청을 보냅니다. 응답은 약속으로 처리되므로 응답을 기다리기 위해 wait를 사용할 수 있습니다.
  • 응답: 응답 본문은 게시물의 JSON 데이터를 포함하는 콘솔에 기록됩니다.

2. POST 요청하기

POST 요청은 서버에 데이터를 보내는 데 사용되며, 종종 새 리소스를 생성합니다. Got를 사용하면 POST 요청으로 JSON 데이터를 쉽게 보낼 수 있습니다.

const got = require('got');

(async () => {
    try {
        const response = await got.post('https://jsonplaceholder.typicode.com/posts', {
            json: {
                title: 'foo',
                body: 'bar',
                userId: 1
            },
            responseType: 'json'
        });
        console.log('POST Request:');
        console.log(response.body);
    } catch (error) {
        console.error('Error in POST request:', error.message);
    }
})();
로그인 후 복사
  • 설명:
  • 엔드포인트: https://jsonplaceholder.typicode.com/posts는 서버에 새 게시물을 생성하는 데 사용됩니다.
  • JSON 데이터: Got 요청의 json 옵션을 사용하면 전송할 데이터를 지정할 수 있습니다. 여기에서는 제목, 본문, 사용자 ID가 포함된 새 게시물을 보냅니다.
  • 응답: 새 ID와 함께 전송된 데이터가 포함된 서버의 응답이 콘솔에 기록됩니다.

3. 오류 처리

HTTP 요청 중에 네트워크 문제나 서버 오류가 발생할 수 있습니다. Got는 이러한 오류를 처리하는 간단한 방법을 제공합니다.

const got = require('got');

(async () => {
    try {
        const response = await got('https://nonexistent-url.com');
        console.log(response.body);
    } catch (error) {
        console.error('Error handling example:', error.message);
    }
})();
로그인 후 복사
  • 설명:
  • 존재하지 않는 URL: 이 예에서는 존재하지 않는 URL에 대해 GET 요청을 시도합니다.
  • 오류 처리: 요청이 실패하면 Got가 자동으로 오류를 발생시킵니다. catch 블록은 이 오류를 캡처하고 오류 메시지를 콘솔에 기록합니다.

Got의 고급 기능

Got은 단순한 GET 및 POST 요청만 수행하는 것이 아닙니다. 더 복잡한 시나리오를 처리하는 데 도움이 되는 여러 가지 고급 기능이 함께 제공됩니다.

1. 요청 옵션 사용자 정의

Got을 사용하면 헤더, 쿼리 매개변수, 시간 초과 등을 설정하여 요청을 맞춤 설정할 수 있습니다.

const got = require('got');

(async () => {
    try {
        const response = await got('https://jsonplaceholder.typicode.com/posts/1', {
            headers: {
                'User-Agent': 'My-Custom-Agent'
            },
            searchParams: {
                userId: 1
            },
            timeout: 5000
        });
        console.log('Customized Request:');
        console.log(response.body);
    } catch (error) {
        console.error('Error in customized request:', error.message);
    }
})();
로그인 후 복사
  • Explanation:
  • Headers: You can set custom headers using the headers option. Here, we set a custom User-Agent.
  • Query Parameters: The searchParams option allows you to add query parameters to the URL.
  • Timeout: The timeout option sets the maximum time (in milliseconds) the request can take before throwing an error.

2. Streaming with Got

Got supports streaming, which is useful for handling large data or working with files:

const fs = require('fs');
const got = require('got');

(async () => {
    const downloadStream = got.stream('https://via.placeholder.com/150');
    const fileWriterStream = fs.createWriteStream('downloaded_image.png');

    downloadStream.pipe(fileWriterStream);

    fileWriterStream.on('finish', () => {
        console.log('Image downloaded successfully.');
    });
})();
로그인 후 복사
  • Explanation:
  • Streaming: The got.stream(url) function initiates a streaming GET request. The data is piped directly to a writable stream, such as a file.
  • File Writing: The fs.createWriteStream() function is used to write the streamed data to a file.

Making HTTP Requests in Node.js with Got

Download the source code here.

Conclusion

Got is a versatile and powerful library for making HTTP requests in Node.js. It simplifies the process of interacting with web services by providing a clean and intuitive API, while also offering advanced features like error handling, timeouts, and streams. Whether you’re building a simple script or a complex application, Got is an excellent choice for handling HTTP requests.

By using Got, you can write cleaner, more maintainable code and take advantage of its robust feature set to meet the needs of your application. So the next time you need to make an HTTP request in Node.js, consider using Got for a hassle-free experience.

Thanks for reading…

Happy Coding!

The post Making HTTP Requests in Node.js with Got first appeared on Innovate With Folasayo.

The post Making HTTP Requests in Node.js with Got appeared first on Innovate With Folasayo.

위 내용은 Got를 사용하여 Node.js에서 HTTP 요청 만들기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!