๐๐ป ํด๊ฒฐ๋ฒ์ ๋งจ์๋์
ํ์คํ๊ตฌํ์ค, ํ๋ก ํธ์์๋ axios ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ฌ์ฉํ์ฌ ๋ฐฑ์๋์ API ์ฐ๋์ ์งํํ๋ ค๊ณ ํ์๋ค. ์ฝ๋์ ์ ์ง๋ณด์์ ์ฌ์ฌ์ฉ์ฑ์ ์ํด http ํด๋ผ์ด์ธํธ๋ฅผ ๋ฐ๋ก ๊ตฌ์ฑํ๋ ์ฝ๋๋ฅผ ๋ง๋ค์๊ณ , exportํ์ฌ axios๋ฅผ ๋ ๋ณด๊ธฐ ์ฝ๊ฒ ์ฌ์ฉํ ์ ์๊ฒ ํ์๋ค.
// http.ts
import axios, { AxiosRequestConfig } from "axios";
const BASE_URL = "http://localhost:3000";
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,
});
axiosInstance.interceptors.response.use(
(response) => {
return response;
},
(error) => {
return Promise.reject(error);
}
);
return axiosInstance;
};
export const httpClient = createClient();
์๋์ ๊ฐ์ด ํด๋ผ์ด์ธํธ๋ฅผ ์ฌ์ฉํ์ฌ ์นดํ ๊ณ ๋ฆฌ๋ฅผ ์์ฒญํ๋ method๋ฅผ ๊ตฌํํ์ฌ ์ฌ์ฉํ์๋ค.
import { Category } from "../models/category.modal";
import { httpClient } from "./http";
export const fetchCategory = async () => {
const response = await httpClient.get<Category[]>("/category");
return response.data;
};
ํ์ง๋ง fetchํด์ ๊ฐ์ง๊ณ ์ฌ๋ CORS ์ค๋ฅ๊ฐ ๋ฐ์ํ๋ค.
ํด๊ฒฐ ๋ฐฉ๋ฒ
1๏ธโฃ Express.js ๊ธฐ์ค, app.js์ ์๋ ์ฝ๋๋ฅผ ์ถ๊ฐํด์ค๋ค.
const cors = require("cors");
const corsOptions = {
origin: "http://localhost:3001", // ํด๋ผ์ด์ธํธ ํฌํธ๋ฒํธ
credentials: true,
};
app.use(cors(corsOptions));
2๏ธโฃ ์๋ฒ์ ํด๋ผ์ด์ธํธ์ ์ฃผ์๋ฅผ ์ ๊ตฌ๋ถํด์ฃผ์๋์ง ํ์ธํด์ค๋ค.
ํ๋ก ํธ์๋ ์ฝ๋์์๋ ์๋ฒ์ ์ฃผ์๋ฅผ ์ฌ๋ฐ๋ฅด๊ฒ ์ ์ด์ฃผ์ด์ผ ํ๋ค.
// http.ts(FE)
const BASE_URL = "http://localhost:3000"; // ์๋ฒ์ ํฌํธ๋ฒํธ
'์ค๋ฅํด๊ฒฐ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ํธ๋ฌ๋ธ์ํ ] vite+react-ts+tailwind ์๋์๋จ ํด๊ฒฐ (0) | 2024.08.16 |
---|---|
[ํธ๋ฌ๋ธ์ํ ] Git ํ์ผ๋ช ๋์๋ฌธ์ ๋ณํ ์ธ์ ๋ถ๊ฐ ๋ฌธ์ (2) | 2024.08.14 |
zsh: command not found: nvm ํด๊ฒฐ (0) | 2024.07.19 |
api.channel.io API ๊ฐ์ ธ์ค๊ธฐ ์๋ฌ ํด๊ฒฐ - plugin key (0) | 2024.06.14 |
TypeError: Cannot destructure property '๋ณ์๋ช ' of 'req.body' as it is undefined. (0) | 2024.06.02 |