🛠️Backend/Spring

[Spring Boot] Spring Boot & React 프로젝트 연결하기

뉴발자 2024. 10. 30.
728x90

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

개요

이전에 만들었던 서버를 화면과 함께 배포해야 되는 상황이 발생했다.

 

서버는 Spring Boot를 사용했고 화면은 React를 사용했다.

 

두 프로젝트를 합쳐서 배포한 작업을 기록으로 남긴다.

 

 

리액트 프로젝트 추가 및 폴더 위치

Spring Boot 프로젝트 내에서 리액트 프로젝트 폴더의 위치는 다음과 같다.

 

기존 서버 프로젝트의 main 폴더 아래에 넣어주었다.

 

만약 기존에 생성했던 리액트 프로젝트가 없다면 터미널에서 해당 위치에 리액트 프로젝트를 생성해주면 된다.

 

 

Proxy 설정

CrossOrigin 에러를 방지하기 위해 리액트 프로젝트에서 Proxy를 설정해준다.

 

필자의 경우 서버에서 CrossOrigin 에러 처리를 하고 있었어서 리액트에서 따로 proxy 설정은 하지않았다.

 

만약 필요하다면 다음과 같은 순서로 Proxy를 설정해주면 된다.

 

1. 리액트 프로젝트의 package.json 파일 안에 아래 코드를 추가한다.

"proxy": "http://localhost:8080",

 

포트는 자신의 프로젝트 포트에 맞춰서 변경해주면 된다.

 

2. Proxy 라이브러리를 설치한다.

npm install http-proxy-middleware --save

 

3. src/main/frontend/src 폴더에 setProxy.js 파일을 생성하고 아래 코드를 추가한다.

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'http://localhost:8080',	# 서버 URL or localhost:설정한포트번호
      changeOrigin: true,
    })
  );
};

 

 

Axios 통신

기존 리액트 프로젝트에서 axios 라이브러리를 사용해서 서버와 통신하고 있었다.

 

주의할 점은 axios를 create 할 때 baseURL을 설정하게 되면 다른 서버로 통신을 요청할 수 있다.

axios.create({
  baseURL: "localhost:8081",
  ...
});

 

따라서 위 설정 없이 axios를 사용하게 되면 서버 ip와 port에 맞춰서 통신을 한다.

axios.get('/api')

 

 

build.gradle 설정

프로젝트 빌드 시 리액트 프로젝트를 포함시키기 위해서 다음과 같은 코드를 추가해준다.

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/build"
	into "$projectDir/src/main/resources/static"
}

 

작성된 내용은 간단히 설명하자면 스프링 부트 프로젝트를 빌드하기 전에 리액트 프로젝트를 먼저 빌드한 후 그 결과물을

 

스프링 부트 빌드 시 포함시킨다는 내용이다.

 

여기까지 한 후 빌드된 jar 파일을 실행시킨 후 인터넷으로 접속해보면 정상적으로 화면이 뜨는 것을 확인할 수 있다.

 

 

참고 사이트

https://velog.io/@u-nij/Spring-Boot-React.js-%EA%B0%9C%EB%B0%9C%ED%99%98%EA%B2%BD-%EC%84%B8%ED%8C%85

 

Spring Boot + React.js 개발환경 연동하기

Spring Boot와 React.js를 연동해 개발환경을 만들고, 빌드해서 jar 파일로까지 만들어보는 과정입니다.

velog.io

 

 

 

 

 

 

 

 

 

 

728x90

댓글