[Spring] 스케줄러 프로젝트[2] - spring과 react 연동 및 빌드하기

RedPanda·2023년 7월 21일
0

프로젝트 초기 설정부터 react 연동까지 해보도록 하겠다.
이 프로젝트는 IntelliJ 유료버전(Ultimate)으로 진행하고 있다.

Spring 초기 세팅

프로젝트 생성

IntelliJ를 깔았다면 Spring Initilizr로 프로젝트를 생성해준다. Gradle로 진행하도록 한다.

다음 화면에서 Dependency를 설정하는데 기본적으로 다음과 같이 추가해준다.

DB 연결 및 Controller 세팅

작동을 확인하기 위해 DB 연결 및 Controller 세팅을 해준다.
사진보다 코드로 설명하는게 나을 것 같다.

우선 프로퍼티 설정으로 DB를 연결해준다.

// src/main/resources/application.properties
-- 필수 사항 --
spring.datasource.driver-class-name=org.mariadb.jdbc.Driver
spring.datasource.url=jdbc:mariadb://localhost:3306/board?
spring.datasource.username=root
spring.datasource.password=root

-- 추가 사항 (없어도 됨) --
allowPublicKeyRetrieval=true&useSSL=false
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update // DB 자동 업데이트
spring.servlet.multipart.maxFileSize=50MB
spring.servlet.multipart.maxRequestSize=50MB // 올리는 사진의 용량 지정
server.port=8002 // localhost:8002번으로 옮김 (기본8080)

이번엔 Controller와 확인할 Page를 설정해준다. Controller를 모르겠다면 해당 포스팅을 읽어보기 바란다. Controller로 페이지 띄우기

package com.example.spring_react_v1.Controller;

import ch.qos.logback.core.model.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class MainController {
    @GetMapping("/")
    public String main(Model model){
        return "home";
    }

}

이렇게 설정하고 'com.example.프로젝트_이름' 에 있는 class 파일을 실행하고 chrome에서 localhost:8002를 열어 작동되는지 확인한다.

폴더 설정은 다음과 같다.

++) spring security를 추후에 사용하기 위해 dependency에 넣어놨는데 지금은 안쓸거니 실행하는 파일의 코드를 다음과 같이 바꿔준다.

package com.example.spring_react_v1;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;

@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class SpringReactV1Application {

    public static void main(String[] args) {
        SpringApplication.run(SpringReactV1Application.class, args);
    }

}

React 세팅

react 프로젝트 생성

spring 내부에 react 프로젝트를 만들어준다. src/main에 만들도록 한다. 추가로 데이터 주고받을때 사용할 axios를 설치해준다.

cd src/main
npx create-react-app 디렉토리_이름
npm install axios --save

완료되었다면 생성한 디렉토리에서 react를 실행해본다.

cd 디렉토리_이름
npm start

이리하면 localhost:3000 으로 react가 켜지는 것을 확인할 수 있다 (Spring은 종료해줘야 함)

Spring에서 React 실행 및 빌드

(*주의) 시작 전에 spring 테스트를 위해 만들어놨던 "/" controller를 지워주자. 밑에서 Controller 설명을 다시 해주겠다.

frontend 설정

우선, CORS에 이용할 프록시 설정을 위해 'src/main/frontend/src' 에서 setupProxy.js 파일을 만들어준다. (이름이 다르면 작동하지 않는다.)
다음을 복사해서 붙여준다.

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

module.exports = function(app) {
    app.use(
        '/api',
        createProxyMiddleware({
            target: 'http://localhost:8002', // backend 서버의 주소
    changeOrigin: true,
		})
	);
};

다음으로 App.js 에서 백에 보낼 요청을 설정해준다. 다음을 그대로 복붙해준다.

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

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

  useEffect(() => {
    axios.get('/api/hello') // 해당 url로 요청을 보냄
        .then(response => setHello(response.data))
        .catch(error => console.log(error))
  }, []);

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

export default App;

backend 설정

Controller에 있는 class 파일을 수정해준다.
"/" 컨트롤러가 있으면 빌드 시에 spring이 그 컨트롤러를 먼저 보기 때문에 react를 띄우지 못한다. (서버와 프론트 따로 키는 데에는 문제 없음)

package com.example.spring_react_v1.Controller;

import ch.qos.logback.core.model.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MainController {
    @GetMapping("/api/hello")
    public String test(Model model){
        return "test data";
    }

}

프로젝트 빌드

spring 프로젝트로 돌아오도록 한다. 현위치가 main이라면'cd ../../' 로 src 뒤로 오도록 한다.

왔으면 build.gradle의 밑에 다음을 추가한다. spring 빌드 전에 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"
}

모두 붙여넣었으면 build를 해보자. 다음을 입력하도록 한다.
jar 파일은 build/libs에 있는 파일인데 이름이 다를 수 있으니 확인해서 입력하도록 하자.

./gradlew build   // 프로젝트 빌드
java -jar build/libs/spring_react_v1-0.0.1-SNAPSHOT.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

profile
끄적끄적 코딩일기

0개의 댓글