반응형

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 임을 꼭 명심하자!! 

 

https://serpiko.tistory.com/873

반응형