axios를 위해 node-fetch를 스크랩하는 방법

Apr 27 2023
node-fetch를 대체하는 이유는 무엇입니까? 전역 구성 예: 기본 URL axios를 사용하면 기본 URL과 같은 전역 구성을 설정할 수 있습니다. 이렇게 하면 특히 호출할 엔드포인트가 여러 개인 경우 HTTP 요청을 더 쉽게 관리할 수 있습니다.
Unsplash의 Harry Dona 사진

node-fetch를 대체하는 이유는 무엇입니까?

글로벌 구성 예: 기본 URL

axios를 사용하면 기본 URL과 같은 전역 구성을 설정할 수 있습니다. 이렇게 하면 특히 호출할 엔드포인트가 여러 개인 경우 HTTP 요청을 더 쉽게 관리할 수 있습니다.

전용 방법

Axios는 게시 및 가져오기와 같은 HTTP 요청을 만들기 위한 전용 메서드를 제공합니다. 이렇게 하면 요청을 할 때마다 요청 방법을 지정하지 않고도 HTTP 요청을 더 쉽게 할 수 있습니다.

인터셉터 지원

Axios는 HTTP 요청 및 응답을 보내거나 받기 전에 수정할 수 있는 인터셉터를 지원합니다. 이는 사용자 지정 헤더를 추가하거나 인증을 수행해야 할 때 유용합니다.

오류 처리가 이상합니다

Axios는 node-fetch보다 더 나은 오류 처리 메커니즘을 가지고 있습니다. Axios는 2XX 이외의 모든 상태 코드에 대해 예외를 발생시켜 애플리케이션의 오류를 더 쉽게 처리할 수 있도록 합니다.

이제 axios가 node-fetch의 더 나은 대안인 이유를 알았으므로 Node.js 애플리케이션에서 node-fetch를 axios로 대체하는 방법을 살펴보겠습니다.

다음은 axios를 위해 node-fetch를 대체하기 위한 가이드입니다. ⛄️

아래의 모든 세부 정보는 다음 환경과 관련이 있습니다.

Node Version > 16 
node-fetch version = 2.0.0
axios version > 1.3.4

콘텐츠 유형: application/x-www-form-urlencoded

URLSearchParams 양식 데이터를 작성하는 데 사용할 것입니다 . 최신 버전의 axios에서는 javascript 객체를 직접 제공할 수 있으며 콘텐츠 유형이 지정되면 자동으로 변환을 처리합니다 application/x-www-form-urlencoded. 이는 문자열 템플릿으로 작업하는 것과 비교할 때 유용합니다.


//node-fetch 
const loginResponse = await fetch("https://login.com", {
      credentials: "include",
      headers: {
        "cache-control": "no-cache",
        "content-type": "application/x-www-form-urlencoded",
      },
      body: `user=${username}&pass=${password}`,
      method: "POST",
      redirect: "manual",
    })

//--------------------------------------------------------------------------
//axios 
const loginResponse = await axios.post(
      "https://login.com",
      new URLSearchParams({
        user: "username",
        pass: "password",
      }),
      {
        headers: {
          "content-type": "application/x-www-form-urlencoded",
        },
      }
    );

JSON.stringify(..)더 이상 요청 본문을 POST 할 필요가 없습니다.

//node-fetch 
const response = await fetch(
    `https://${process.env.AUTH0_DOMAIN}/oauth/token`,
    {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify({
        grant_type: "client_credentials",
        client_id: process.env.AUTH0_KEY,
        client_secret: process.env.AUTH0_SECRET,
        audience: `https://${process.env.AUTH0_DOMAIN}/api/v2/`,
      }),
    }
  );

//--------------------------------------------------------------------------
//axios 

const response = await axios.post(
    `https://${process.env.AUTH0_DOMAIN}/oauth/token`,
        {
          grant_type: "client_credentials",
          client_id: process.env.AUTH0_KEY,
          client_secret: process.env.AUTH0_SECRET,
          audience: `https://${process.env.AUTH0_DOMAIN}/api/v2/`,
      },
      {
          headers: { "content-type": "application/json" 
      });

모든 상태 코드에 대해 res 객체를 수동으로 확인해야 합니다. 이외 의 axios모든 상태 코드에 대해 예외가 발생합니다.2XX

//node-fetch 
let res = await fetch(`https://${domain}/api/v2/users/${userId}`, 
{  method: "GET",
   headers: {
              Authorization: `Bearer ${managementToken}`,
              "content-type": "application/json",
            },
 });

if (!res.ok) {
  throw new BadRequest(res.statusText);
}

//--------------------------------------------------------------------------
//axios
try {
      await axios.delete(`https://${domain}/api/v2/users/${userId}`, {
        headers: {
        Authorization: `Bearer ${managementToken}`,
        "content-type": "application/json",
         },});
} catch ({ message }) {

        throw new BadRequest(message);
}

쿠키로 작업하는 경우 이 트릭을 사용하면 많은 시간을 절약할 수 있습니다. ⏰

302axios 의 예외이므로 사용 가능한 구성 옵션을 사용하여 명시적으로 처리해야 합니다. 유효한 것으로 간주되는 validateStatus기능을 수동으로 재정의하는 기능을 사용합니다.status code

Max redirects요청이 따르는 리디렉션 수를 제한하는 데 사용할 수 있습니다(노드에서만 사용 가능).

//node-fetch

const loginResponse = await fetch("https://login.com", {
      credentials: "include",
      headers: {
        "content-type": "application/x-www-form-urlencoded",
      },
      method: "POST",
      redirect: "manual",
    });

//--------------------------------------------------------------------------
//axios
const loginResponse = await axios.post(
      "https://login.com",
      {
        headers: {
          "content-type": "application/x-www-form-urlencoded",
        },
        maxRedirects: 0, //we need values for cookies for next request
        validateStatus: function (status) {
          return status >= 200 && status <= 302;
        },
      }
    );

node-fetch와 사이의 주목할만한 차이점 중 하나는 axiosHTTP 요청을 처리하는 방식입니다. 를 사용하면 node-fetch각 가져오기 호출에 요청의 "방법"을 제공해야 합니다. 반면에 axios사용자의 필요에 맞는 전용 메서드 호출을 제공하여 문제를 해결합니다. axios.post()예를 들어 POST 요청, axios.get()GET 요청 등에 사용할 수 있습니다 .

다음은 전용 메서드를 사용하는 방법의 예입니다 axios.

//node-fetch 
const response = await fetch(
  `https://${process.env.AUTH0_DOMAIN}/oauth/token`,
  { method: "POST",
    headers: { "content-type": "application/json" }, ...}

const response = await fetch(
  `https://${process.env.AUTH0_DOMAIN}/oauth/token`,
  { method: "GET" ...}

//--------------------------------------------------------------------------
//axios
const response = await axios.post(
  `https://${process.env.AUTH0_DOMAIN}/oauth/token`,
  {
    headers: { "content-type": "application/json" },
    // other config options
  }
);

const response = await axios.get(
  `https://${process.env.AUTH0_DOMAIN}/oauth/token`,
  {
    // other config options
  }
);

node-fetch와 사이의 또 다른 차이점은 axios구성에 사용하는 변수 이름입니다. 목록이 길지만 다음은 자주 사용되는 몇 가지 예입니다.

  • credentials: "include"in 의 init 객체는 in 의 config 객체를 node-fetch참조합니다 .withCredentials: trueaxios
  • redirect: "manual"in 의 init 객체는 in 의 config 객체를 node-fetch참조합니다 .maxRedirects: 0axios

에서는 or 메서드를 node-fetch사용하여 응답을 명시적으로 생성해야 합니다 . 예를 들어:.json().text()

const response = await fetch('https://${process.env.AUTH0_DOMAIN}/oauth/token')
if (!response.ok) {
  throw new Error('Failed to fetch data')
}
const data = await response.json()

try {
  const response = await axios.get('https://${process.env.AUTH0_DOMAIN}/oauth/token')
  const data = response.data
} catch (error) {
  console.error(error)
}

요약하면 node-fetchNode.js에서 HTTP 요청을 만들기 위한 좋은 라이브러리이지만 axios더 많은 고급 기능과 더 나은 개발자 경험을 제공합니다. 를 사용하면 axios전역 구성, 전용 메서드, 인터셉터 지원 및 더 나은 오류 처리를 얻을 수 있으므로 많은 시간과 노력을 절약할 수 있습니다.

현재 사용 중이고 node-fetch로 전환하려는 경우 axios마이그레이션 프로세스는 비교적 간단합니다. axios의 구문을 사용하고 해당 기능을 활용하도록 코드를 업데이트하십시오 .

내가 뭔가를 놓친 것 같아? 아래 댓글로 알려주세요

첫 글인데 박수와 응원 부탁드려요