springboot + (react+vite) 연동

요한·2025년 6월 20일

front

목록 보기
3/4

이번에는 프로젝트를 springboot+react 를 사용해서 개발을 진행하기 때문에 cors 방지및 연동을 위해 설정을 하겠습니다

react

vite.config.ts

export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:8080',
        changeOrigin: true,
      }
    }
  }
}) // 기본적인 api 설정 

proxy설정을 "/api"로 설정하면 prefix의미로 http://localhost:8080/api/** 에 모든 데이터를 받겠다는거다!

App.tsx

const [test,setTest] = useState('');
  
  useEffect(() => {
    fetch('/api')
      .then((res) => res.text()) 
      .then((data) => setTest(data))
      .catch((err) => console.error(err));
  }, []);

localhost:8080/api 요청한 데이터를 test에 넣어서 보관한다!

return (
    
    <h1 className="text-red-500 sm:text-black">
    Hello world!

    <h3>받아온 데이터는{test} </h3>
  </h1>
  )

springboot

백엔드 설정 필수!
참고: cors 방지 https://velog.io/@dev_yohan/springboot-cros-%EC%84%A4%EC%A0%95

TestController

@RestController
public class TestController {
    @GetMapping("/api")
    public HttpEntity<String> index(){
        String response = "Hello World";
        return new HttpEntity<>(response);
    }
}

결과

성공!

vite

그냥 react + springboot 연동할땐 middlewareProxy 따로 다운받아줘야하는 걸로 아는데 왜 되는걸까 ? vite가 개발서버에서 Proxy를 내장해서 가능했던것이다! vite 짱

글 읽어주셔서 감사합니다 :)

profile
코드 깍는 개발자 kangyohan.dev.0421@gmail.com

0개의 댓글