Recent Posts
Recent Comments
«   2025/04   »
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
관리 메뉴

ㅇ.ㅇ

[Spring] React 라우팅을 위한 SPA 서버 세팅 본문

Today I Learned

[Spring] React 라우팅을 위한 SPA 서버 세팅

dbs_ 2025. 4. 20. 20:25
반응형

배경

Spring Boot에 React 빌드 파일을 통합한 후 서버를 실행했지만, 라우팅 경로로 직접 접근할 경우 404 Not Found 오류가 발생했다.

 

이유

React의 라우팅 문제

  • React에서는 react-router-dom을 사용해 클라이언트 사이드에서 라우팅을 처리한다. 
  • 예를 들어, 사용자가 /login, /mypage 등으로 직접 URL 경로에 접근하면, 서버는 해당 경로에 정적 파일이 없기 때문에 404 에러를 반환한다. 
  • 하지만 SPA인 React 앱은 모든 라우팅을 클라이언트 측에서 처리해야 하므로, 서버는 모든 경로 요청을 `index.html`로 포워딩하여 React가 적절한 화면을 렌더링할 수 있도록 해야 한다.

 

설정

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/{spring:[a-zA-Z0-9-_]+}").setViewName("forward:/index.html");
		// 루트 경로 1단계 URL에 대해 /index.html로 포워딩 (/login)
        
        registry.addViewController("/**/{spring:[a-zA-Z0-9-_]+}").setViewName("forward:/index.html");
		// 다단계 URL도 index.html로 포워딩 (/users/1)
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
        // 정적 리소스 요청은 그대로 전달하도록 설정 (/static/js, /static/css)
    }
}
  • 물론 일반적인 스프링 프레임워크에서는 설정이 조금 다르다. 

 

반응형

'Today I Learned' 카테고리의 다른 글

[Spring] RestTemplate  (0) 2025.04.09
[Git] Rebase  (0) 2025.03.31
[DEV] curl  (0) 2025.03.30
[Tomcat] Tomcat의 war-tracker 파일  (0) 2025.03.28
[Git] Stash  (0) 2025.03.23