[Spring Boot + React + Expo] Spring Boot + Vite-React 연동 + CORS 설정

Hayden·2025년 4월 7일
0

Java 11, spring Boot 2.7.17

Vite-React 생성

Spring Boot 프로젝트를 생성 후 터미널 cd 명령어를 사용해 프로젝트 디렉토리까지 들어온 후 Vite-React + Typescript를 생성합니다.

터미널에서 /src/main로 이동 후 아래 명령어를 실행합니다.

npm create vite@latest react-tutorial -- --template react-ts

아래 명령어를 통해 리액트 프로젝트가 정상적으로 실행되는지 확인합니다.

npm run dev

CORS 설정

1. 프론트 CORS 설정

개발 환경에서 API 요청을 프록시 서버를 통해 백엔드로 전달합니다.

vite-config.json에 프록시 설정을 해줍니다.

  server: {
    proxy: {
      "/api": {
        target: "http://localhost:8090",
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, ""),
        secure: false,
        ws: true,
      }
    }
  }

target :
rewrite : 프록시를 통해 백엔드로 요청을 보낼 때, URL을 수정하는 역할을 한다. ex)

2. 백엔드 CORS 설정

CORS 설정을 통해 특정 도메인에서 백엔드에 대한 요청을 허용합니다.

WebConfig.java를 생성하고 WebMvcConfigurer 인터페이스를 구현하고 React 개발 서버의 도메인(http://localhost:5173)을 허용하도록 설정합니다.

WebConfig.java

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Value("${cors.allowed.origins}")
    private String allowedOrigins;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOrigins("http://localhost:8081",
//                        "http://192.168.0.5:8090",
                        "http://localhost:5173")
                .allowCredentials(true)
                .allowedMethods("*")
                .allowedHeaders("*");

    }
}

리액트 빌드 자동화

def frontendDir = "$projectDir/src/main/frontend"

sourceSets {
    main {
        resources { srcDirs = ["$projectDir/src/main/resources"]
        }
    }
}

processResources { dependsOn "copyReactBuildFiles" }

task installReact(type: Exec) {
    workingDir "$frontendDir"
    inputs.dir "$frontendDir"
    group = BasePlugin.BUILD_GROUP
    if (System.getProperty('os.name').toLowerCase(Locale.ROOT).contains('windows')) {
        commandLine "npm.cmd", "audit", "fix"
        commandLine 'npm.cmd', 'install' }
    else {
        commandLine "npm", "audit", "fix" commandLine 'npm', 'install'
    }
}

task buildReact(type: Exec) {
    dependsOn "installReact"
    workingDir "$frontendDir"
    inputs.dir "$frontendDir"
    group = BasePlugin.BUILD_GROUP
    if (System.getProperty('os.name').toLowerCase(Locale.ROOT).contains('windows')) {
        commandLine "npm.cmd", "run-script", "build"
    } else {
        commandLine "npm", "run-script", "build"
    }
}

task copyReactBuildFiles(type: Copy) {
    dependsOn "buildReact"
    from "$frontendDir/dist"
    into "$projectDir/src/main/resources/static"
}

Gradle 빌드 시 자동으로 frontend 디렉토리에 있는 React 애플리케이션을 빌드하고, 빌드된 파일을 프로젝트의 resources/static 디렉토리로 복사하는 작업을 수행하는 스크립트입니다.

profile
백엔드 공부

0개의 댓글