반응형
vite.config.ts 파일 설정을 통해서 proxy 를 적용할 수 있다.
API를 적용하기 위해서 jsonplaceholder 의 https://jsonplaceholder.typicode.com/todos/1 로 예를 들어보자.
이때 proxy를 설정할때 주의사항은 secure에 false를 해야한다.
그렇지 않으면 아래와 같이 http proxy error가 뜬다.

vite.config.ts
import { defineConfig } from 'vite' import preact from '@preact/preset-vite' // https://vitejs.dev/config/ export default defineConfig({ plugins: [preact()], server: { proxy: { "/api": { target: "https://jsonplaceholder.typicode.com/todos", changeOrigin: true, secure: false, rewrite: (path) => path.replace(/^\/api/, ""), }, }, }, })
3. proxy 설정된 /api 를 사용
app.tsx 에서는 다음과 같이 사용한다
import { useState } from 'preact/hooks' import preactLogo from './assets/preact.svg' import './app.css' export function App() { // proxy 적용 (async function () { await fetch( "/api/1" ).then((response) => { console.log(response); }); })(); return (<div></div>); }
정리
이때 request를 할 때 api/1이 아닌 /api/1 임을 꼭 명심하자!!

반응형
'Basic > React' 카테고리의 다른 글
nextjs에서 파일에 []를 사용하는 이유 (0) | 2023.02.17 |
---|---|
[React] Realtime으로 데이터 주고받기 (0) | 2023.02.09 |
[React] export 'Switch' (imported as 'Switch') was not found in 'react-router-dom' (0) | 2023.02.03 |
[React] <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment> (0) | 2023.02.01 |
[React] SPA 프레임 워크 (0) | 2023.01.24 |