Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

사고쳤어요

[React / ts] Book Store 만들기 - ⑥ Axios 사용과 웹서버 연결 본문

웹 풀스택

[React / ts] Book Store 만들기 - ⑥ Axios 사용과 웹서버 연결

kevinmj12 2025. 4. 21. 19:02

https://www.npmjs.com/package/axios

 

axios

Promise based HTTP client for the browser and node.js. Latest version: 1.8.4, last published: a month ago. Start using axios in your project by running `npm i axios`. There are 152098 other projects in the npm registry using axios.

www.npmjs.com

JavaScript, TypeScript에서 가장 대중적으로 사용되는 통신 라이브러리이다.

npm i axios

 

 

// http.ts

import axios, { AxiosRequestConfig } from "axios";

const BASE_URL = "http://localhost:9999";
const DEFAULT_TIMEOUT = 30000;

export const createClient = (config?: AxiosRequestConfig) => {
  const axiosInstance = axios.create({
    baseURL: BASE_URL,
    timeout: DEFAULT_TIMEOUT,
    headers: {
      "content-type": "application/json",
    },
    withCredentials: true,
    ...config,
  });

  axios.interceptors.response.use(
    (response) => {
      return response;
    },
    (error) => {
      return Promise.reject(error);
    }
  );

  return axiosInstance;
};

export const httpClient = createClient();

위와 같이 기본적으로 사용될 틀을 작성해준다.

이제부터 통신을 위해 새로운 내용을 작성할 때마다 저 틀을 통해서 기본적인 내용을 갖출 수 있게 되었다.

 

// category.api.ts

import { Category } from "../models/category.model";
import { httpClient } from "./http";

export const fetchCategory = async () => {
  const response = await httpClient.get<Category[]>("/categories");
  return response.data;
};

예를 들어 category를 받아오는 get 메소드를 실행하는 fetchCategory는 위와 같다.

httpClient를 통해 구조를 받아오고 간단하게 path와 get, <Category[]>등만을 추가로 설정해주었다.

 

백엔드와 연결

아무런 사전 작업 없이, 9999번 포트에 서버를 띄우고 프론트엔드에서 연결을 시도하려 하면 에러가 발생할 것이다.

 

AxiosError {message: 'Network Error', name: 'AxiosError', code: 'ERR_NETWORK',

 

위 에러는 CORS 에러로 서버에서 등록하지 않은 도메인으로부터 접속이 시도되어 에러가 발생한 것이다.

이를 해결하기 위해 먼저 백엔드 환경에서 cors 라이브러리를 설치해준다.

npm i cors

 

그리고 다음 내용을 추가해준다.

const cors = require("cors");


app.use(
  cors({
    origin: "http://localhost:3000",
    credentials: true,
  })
);

 

위와 같이 설정을 해주면 프론트엔드에서 접속이 정상적으로 이루어진다.