본문 바로가기
Projects/센서 모니터링 시스템

[센서 모니터링 시스템] 10. React 개발환경 구성

by DevJaewoo 2022. 8. 19.
반응형

Intro

아래의 글을 참고하여 개발환경을 구성했다.

https://velog.io/@u-nij/Spring-Boot-React.js-개발환경-세팅

 

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

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

velog.io


React APP 생성

시작하기 전 npx 명령어를 사용하기 위해 Node.JS를 설치해야 한다.

아래의 링크에서 다운로드 받을 수 있다.

https://nodejs.org/ko/download/

 

다운로드 | Node.js

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

nodejs.org

 

 

Spring Boot 프로젝트는 이미 만들어져있으니, main 패키지에 React App을 설치해준다.

NodeJS가 설치되어야 진행이 가능하다.

 

cd src/main
npx create-react-app frontend	# frontend: 프로젝트명

 

설치가 완료되면 frontend 프로젝트 폴더로 들어가 React 앱을 실행시킨다.

cd frontend
npm start

 

https://localhost:3000 으로 접속했을 때 아래와 같은 화면이 뜨면 된다.

React 실행 페이지


Proxy 설정

CORS 관련 오류를 방지하기 위해 프록시를 설정해야 된다고 한다.

원글에는 setProxy라고 나와있는데, 이제는 파일명을 setupProxy로 해야 한다.

setProxy로 해도 오류는 안나지만 Proxy가 동작을 안한다.

 

우선 필요한 모듈을 설치한다.

npm install http-proxy-middleware --save

 

그 다음 프록시 코드를 작성해준다.

 

frontend/src/setupProxy.js

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

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

 

만약 프록시가 정상적으로 적용됐다면 앱을 실행할 때 아래와 같이 Proxy created라는 문구가 뜬다.

PS D:\workspace\Projects\sensor-monitoring-system\Server\src\main\frontend> npm start

> frontend@0.1.0 start
> react-scripts start

[HPM] Proxy created: /  -> http://localhost:8080

Axios를 통한 API Request

Spring 서버에 Request 테스트용 Controller를 하나 만들어보자.

HelloController.java

@Controller
public class SensorController {

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

 

그리고 App.js에 아래의 코드를 붙여넣고 다시 실행하자.

import React, {useEffect, useState} from 'react';
import axios from 'axios';

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

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

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

export default App;

 

아래와 같이 HelloController에서 보내준 메시지가 잘 출력되는것을 볼 수 있다.

데이터 요청 테스트

Spring과 React를 하나의 jar 파일로 빌드하기 위해 build.gradle 하단에 아래의 코드를 추가하고 Sync 한다.

// + React
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"
}
// - React

 

Sync 완료 시 Gradle에 buildReact가 생성된다.

이 상태에서 build를 실행하면 React가 webpack을 통해 변환되어 Spring 서버와 통합되어 빌드된다.

Gradle Task 목록

 

아래의 명령어를 통해 빌드된 서버를 실행시킬 수 있다.

.\gradlew build
java -jar build/libs/*-SNAPSHOT.jar
반응형