본문 바로가기

카테고리 없음

[ 자바스크립트 / JavaScript ] node-fetch 가져와서 사용하기

반응형

Node.js에서 node-fetch 모듈을 require로 가져오는 방법에 대해 설명드리겠습니다. node-fetch는 Fetch API를 Node.js 환경에서 사용할 수 있게 해주는 라이브러리로, HTTP 요청을 보내는 데 사용됩니다.

1. node-fetch 설치 및 가져오기

1. 프로젝트 디렉토리 설정

먼저, 프로젝트 디렉토리를 설정합니다. 새로운 디렉토리를 만들고 해당 디렉토리로 이동합니다:

mkdir fetch-example
cd fetch-example

2. Node.js 프로젝트 초기화

npm init 명령어를 사용하여 package.json 파일을 생성합니다. 이 파일은 프로젝트의 의존성과 스크립트를 관리합니다:

npm init -y

-y 플래그는 기본값을 사용하여 package.json을 자동으로 생성합니다.

3. node-fetch 설치

다음으로, node-fetch 모듈을 설치합니다:

npm install node-fetch

이 명령어는 node-fetch를 프로젝트의 의존성으로 추가하고, node_modules 폴더에 설치합니다.

4. node-fetch 가져오기

이제 node-fetch를 프로젝트 코드에서 사용할 수 있도록 require로 가져옵니다. 이를 위해 JavaScript 파일을 생성하고, require 문을 추가합니다.

예를 들어, fetch-example.js 파일을 생성하고, 다음과 같이 작성합니다:

const fetch = require('node-fetch');

// Fetch API를 사용하여 데이터를 가져오는 예제
async function fetchData(url) {
    try {
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        console.log('Fetched Data:', data);
    } catch (error) {
        console.error('Error:', error);
    }
}

// 사용 예제
const url = 'https://jsonplaceholder.typicode.com/posts/1';
fetchData(url);

위의 코드에서 require('node-fetch')node-fetch 모듈을 가져와 fetch 변수에 할당합니다. 이를 통해 fetch 함수를 사용하여 HTTP 요청을 보낼 수 있습니다.

2. ESM 지원 버전 (import 사용)

Node.js 12 이상에서는 ESM(ECMAScript Module) 형식으로 모듈을 가져올 수 있습니다. node-fetch 버전 3.x 이상에서는 ESM을 기본적으로 지원하며, require 대신 import를 사용해야 합니다. ESM을 사용할 경우 node-fetch를 가져오는 방법은 다음과 같습니다.

1. package.json 파일 수정

package.json 파일에 "type": "module"을 추가하여 ESM을 사용하도록 설정합니다:

{
  "name": "fetch-example",
  "version": "1.0.0",
  "main": "fetch-example.js",
  "type": "module", // ESM 사용 설정
  "scripts": {
    "start": "node fetch-example.js"
  },
  "dependencies": {
    "node-fetch": "^3.0.0"
  }
}

2. importnode-fetch 가져오기

fetch-example.js 파일에서 require 대신 import 구문을 사용하여 node-fetch를 가져옵니다:

import fetch from 'node-fetch';

// Fetch API를 사용하여 데이터를 가져오는 예제
async function fetchData(url) {
    try {
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        console.log('Fetched Data:', data);
    } catch (error) {
        console.error('Error:', error);
    }
}

// 사용 예제
const url = 'https://jsonplaceholder.typicode.com/posts/1';
fetchData(url);

이렇게 하면 ESM 스타일로 node-fetch 모듈을 가져와 사용할 수 있습니다. node-fetch 버전 3.x 이상에서는 이 방법이 권장됩니다.

3. CommonJS와 ESM 차이

Node.js에서는 두 가지 모듈 시스템을 사용할 수 있습니다:

  1. CommonJS (CJS): require로 모듈을 가져오는 전통적인 방식. Node.js의 기본 모듈 시스템입니다.
  2. ECMAScript Modules (ESM): import로 모듈을 가져오는 최신 방식. Node.js 12 이상에서 package.json 파일에 "type": "module"을 추가하여 사용할 수 있습니다.

node-fetch 버전 3.x 이상에서는 ESM 형식이 기본이므로, import 구문을 사용하는 것이 표준입니다. 그러나 호환성이나 기존 프로젝트와의 일관성을 위해 node-fetch 버전 2.x 이하를 사용하면 require로 가져올 수 있습니다.

4. 요약

  • node-fetch 설치: npm install node-fetch
  • CommonJS (require) 방식:
    • node-fetch 버전 2.x 이하 사용
    • const fetch = require('node-fetch');
  • ESM (import) 방식:
    • node-fetch 버전 3.x 이상 사용
    • import fetch from 'node-fetch';
    • package.json"type": "module" 추가

이제 Node.js에서 node-fetch를 사용하여 HTTP 요청을 수행하는 방법을 알고, requireimport 두 가지 방식으로 사용할 수 있게 되었습니다.
node-fetch는 Node.js 환경에서 Fetch API를 사용할 수 있게 해주는 라이브러리입니다. 이를 통해 클라이언트 사이드 JavaScript에서 사용하던 Fetch API와 유사한 방식으로 HTTP 요청을 보낼 수 있습니다. Node.js에서 node-fetch를 사용하는 방법을 단계별로 설명하겠습니다.

5. 설치

먼저 node-fetch 라이브러리를 설치해야 합니다. 프로젝트 디렉토리에서 다음 명령어를 실행하여 node-fetch를 설치합니다:

npm install node-fetch

6. 기본 사용법

node-fetch를 사용하여 간단한 HTTP GET 요청을 보내고 응답을 처리하는 기본적인 방법을 설명하겠습니다.

GET 요청

아래는 node-fetch를 사용하여 GET 요청을 보내는 예제입니다:

import fetch from 'node-fetch';

// GET 요청 보내기
fetch('https://jsonplaceholder.typicode.com/posts/1')
    .then(response => {
        // 응답 상태 코드 확인
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        // JSON 형태로 응답 데이터 변환
        return response.json();
    })
    .then(data => {
        console.log('Fetched Data:', data);
    })
    .catch(error => {
        console.error('Error:', error);
    });

이 코드는 https://jsonplaceholder.typicode.com/posts/1 URL에 GET 요청을 보내고, 응답 데이터를 JSON으로 파싱하여 콘솔에 출력합니다.

GET 요청 (async/await 사용)

async/await 구문을 사용하여 GET 요청을 더 가독성 있게 처리할 수 있습니다:

import fetch from 'node-fetch';

async function fetchData() {
    try {
        const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        console.log('Fetched Data:', data);
    } catch (error) {
        console.error('Error:', error);
    }
}

fetchData();

이 코드는 위와 동일한 작업을 async/await을 사용하여 수행합니다.

7. POST 요청

node-fetch를 사용하여 POST 요청을 보내는 방법도 간단합니다. 요청 본문에 데이터를 포함하고, 요청 헤더를 설정하는 방법을 알아보겠습니다.

import fetch from 'node-fetch';

// POST 요청 보내기
fetch('https://jsonplaceholder.typicode.com/posts', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({
        title: 'foo',
        body: 'bar',
        userId: 1
    })
})
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('Posted Data:', data);
    })
    .catch(error => {
        console.error('Error:', error);
    });

이 코드는 https://jsonplaceholder.typicode.com/posts URL에 POST 요청을 보내고, JSON 형식으로 데이터를 전송합니다. 요청 헤더에 Content-Type: application/json을 설정하여 요청 본문이 JSON 데이터임을 서버에 알립니다.

8. 요청 옵션

node-fetch에서는 다양한 요청 옵션을 설정할 수 있습니다. 몇 가지 유용한 옵션을 소개합니다:

  • method: HTTP 요청 메서드 (GET, POST, PUT, DELETE, 등)
  • headers: 요청 헤더 설정
  • body: 요청 본문 (POST, PUT 등의 요청에 필요)
  • timeout: 요청 제한 시간 설정
  • redirect: 리다이렉트 정책 설정 (follow, manual, error)

예를 들어, 요청 제한 시간을 설정하고, 리다이렉트 정책을 변경하는 방법은 다음과 같습니다:

import fetch from 'node-fetch';

async function fetchWithTimeoutAndRedirect() {
    try {
        const response = await fetch('https://jsonplaceholder.typicode.com/posts/1', {
            method: 'GET',
            timeout: 5000, // 5초 제한 시간 설정
            redirect: 'follow' // 리다이렉트 정책 설정
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        console.log('Fetched Data with timeout and redirect:', data);
    } catch (error) {
        console.error('Error:', error);
    }
}

fetchWithTimeoutAndRedirect();

9. 에러 처리

HTTP 요청이 실패하거나 서버에서 오류 상태 코드를 반환할 경우, 이를 처리하는 방법을 알아봅시다. response.ok를 사용하여 응답이 성공적인지 확인하고, 그렇지 않을 경우 에러를 던집니다.

import fetch from 'node-fetch';

async function fetchWithErrorHandling() {
    try {
        const response = await fetch('https://jsonplaceholder.typicode.com/posts/invalid-url');
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        console.log('Fetched Data:', data);
    } catch (error) {
        console.error('Request failed:', error);
    }
}

fetchWithErrorHandling();

이 예제에서는 잘못된 URL로 요청을 보내서, 에러가 발생했을 때 이를 처리하는 방법을 보여줍니다.

10. 커스텀 헤더와 인증

API 요청 시 인증 헤더나 다른 커스텀 헤더를 추가해야 할 때가 있습니다. headers 옵션을 사용하여 이를 설정할 수 있습니다.

import fetch from 'node-fetch';

async function fetchWithCustomHeaders() {
    try {
        const response = await fetch('https://jsonplaceholder.typicode.com/posts/1', {
            headers: {
                'Authorization': 'Bearer your-token-here',
                'Custom-Header': 'CustomHeaderValue'
            }
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        console.log('Fetched Data with custom headers:', data);
    } catch (error) {
        console.error('Error:', error);
    }
}

fetchWithCustomHeaders();

이 예제에서는 인증 토큰을 포함한 요청을 보내는 방법을 보여줍니다.

11. 전체 예제

여러 기능을 포함한 전체 예제를 살펴보겠습니다. 이 예제에서는 GETPOST 요청을 수행하고, 에러 처리와 함께 데이터를 로깅합니다.

import fetch from 'node-fetch';

// GET 요청 예제
async function getData(url) {
    try {
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        const data = await response.json();
        console.log('GET Data:', data);
    } catch (error) {
        console.error('GET request failed:', error);
    }
}

// POST 요청 예제
async function postData(url, payload) {
    try {
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(payload)
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        console.log('POST Data:', data);
    } catch (error) {
        console.error('POST request failed:', error);
    }
}

// 사용 예제
const apiUrl = 'https://jsonplaceholder.typicode.com/posts';
getData(apiUrl + '/1'); // 특정 게시물 가져오기
postData(apiUrl, { title: 'foo', body: 'bar', userId: 1 }); // 새로운 게시물 추가

이 전체 예제는 GET 요청으로 특정 게시물을 가져오고, POST 요청으로 새로운 게시물을 추가하는 두 가지 기능을 포함합니다.

이제 node-fetch를 사용하여 Node.js에서 HTTP 요청을 수행하는 다양한 방법을 알게 되셨습니다. 이를 통해 외부 API와의 통신을 쉽게 구현할 수 있습니다.

반응형