리액트+스프링 연동

정원·2023년 3월 29일

React+Spring

목록 보기
2/8

리액트 스프링 연동

리액트+스프링 연동 Test.

기존 홍팍(유튜브)에서 만들었던 스프링부트 프로젝트에 리액트 연동 Test진행하기.

스프링부트에 리액트 설치

IntelliJ 터미널에 CRA 설치.

cd src/main
npx create-react-app frontend


설치 후 실행 Test.

npm start

Proxy 설정 (공식문서)

CORS 관련 오류를 방지하기 위해 proxy 설정.

CORS (Cross Origin Resource Sharing)
서버와 클라이언트가 동일한 IP주소에서 동작하고 있다면, resource를 제약 없이 서로 공유할 수 있지만, 만약 다른 도메인에 있다면 원칙적으로 어떤 데이터도 주고받을 수 없도록 하는 매커니즘입니다.

package.json 파일 이동후 아래 설정 구문 추가

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

Axios를 이용한 서버 통신

Axios란 백엔드와 프론트엔드 사이의 통신을 쉽게 하기 위해 사용하는 라이브러리입니다.

src/main/frontend 폴더에서 axios를 설치해줍니다.

npm install axios --save

src/main/frontend/src/App.js의 내용을 지우고 아래 코드를 붙여넣기

import './App.css';
import React, {useEffect, useState} from 'react';
import axios from 'axios';

function App() {
    const [hello, setHello] = useState('');

    useEffect(() => {
        axios.get('/hello')
             .then(response => setHello(response.data))
             .catch(error => console.log(error))
        }, []);

        return (
            <div>
                백엔드에서 가져온 데이터입니다. : {hello}
            </div>
        )
  
}

export default App;

HelloWorldController.java 생성

@RestController
public class HelloWorldController {

    @GetMapping("/hello")
    public String test() {
        return "Hello, world!!";
    }
}

프로젝트 실행하고 리액트도 npm start

빌드하기

build.gradle 파일 하단에 코드를 추가합니다. SpringBoot 프로젝트가 build 될 때 React 프로젝트가 먼저 build되고, 결과물을 SpringBoot 프로젝트 build 결과물에 포함시킨다는 스크립트입니다.

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"
}

홈 디렉토리로 빠져나와 빌드를 실행합니다.

./gradlew build

BUILD SUCCESSFUL 메세지가 보인다면, build/libs 폴더에 jar 파일로 결과물이 생성되어 있을 겁니다.

java -jar build/libs/firstproject-0.0.1-SNAPSHOT.jar

성공적으로 실행된 모습입니다! 포트번호가 8080으로 바뀐 것을 확인할 수 있습니다.

기존에 작업했던 리액트 파일들을 인텔리제이에 넣기.

http://localhost:8080/ 으로 접속 성공..

0개의 댓글