3월 협업 프로젝트(1석 4조) 👨‍👩‍👧‍👦

협업 spring boot + React -- ts

엄성준 2023. 3. 29. 13:01

우리 팀의 프로젝트는 Front는 React -- ts를 통해서 구성하고 Back은 Spring boot를 통해서 구상하기로 하였다.

 

Back-end 분들은 작업 Tool로 Intellij를 이용하시고 Front는 VScode를 이용하기로 하였다.

 

먼저 Project를 구축하기 위해 https://start.spring.io/ 접속하였다.

 

예전에 김영한 선생님 강의를 볼 때 제외하고 처음이었다.

 

 

Group명을 제외하고 나머지는 이렇게 작성한 듯싶다.

 

그 후 GENERATE를 통해서 파일을 내려받았다.

 

그 후 아래의 링크의 내용을 적어주신 분의 글을 참고하여서 개발환경을 구축하였는데

 

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

 

다른 부분이 있다면 CRA를 통해서 Fontend파일을 구축하지 않았고 VIte를 통해서 구축하였다.

 

그래서 이전에 VScode를 통해서 frontend폴더를 생성하였고 작업환경을 다 구축한 뒤에 main아래에 붙여 넣었다.

 

그 후 CORS 관련 오류를 방지하기 위해 proxy설정을 하였다.

 

먼저 setProxy.js파일을 src/main/frontend/src 폴더에 생성하였고 아래의 코드를 붙여 넣었다.

 

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

module.exports = function(app) {
    app.use(
        '/hello',
        createProxyMiddleware({
            target: 'http://localhost:8080',
    changeOrigin: true,
})
);
};

이제 프론트에서 '/hello'로 요청을 보내면, 백엔드 8080 포트로 요청이 도착하게 된다.

 

그 후 src/main/frontend/src/App.tsx에 내용을 지우고 아래 코드를 넣었다.

 

그전에 axios를 사용하기 위해서는 아래의 명령어를 통해서 axios를 설치해야 한다.

npm install axios --save
import { useEffect, useState } from "react";
import axios from "axios";

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

  useEffect(() => {
    axios
      .get("http://localhost:8080/hello")
      .then((response) => setHello(response.data));
  }, []);

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

export default App;

 

그 후 백엔드에서 java/패키지명/Controller라는 패키지를 생성하고 그 밑에 HelloWorldController라는 클래스 파일을 생성해 주었고 내용은 다음과 같다.

 

package team.compass.Controller;


import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloWorldController {
    @GetMapping("/hello")
    public String test() {
        return "제로베이스 1석 4조 화이팅";
    }
}

이후에도 CORS 관련 오류를 방지하기 위해 몇 가지를 더 해주었는데 먼저 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/dist"
   into "$projectDir/src/main/resources/static"
}

 

그 후 java/패키지명 루트에 CompassApplication이 있는 부분에 WebConfig를 생성하였고 아래의 내용을 넣었다.

package team.compass;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .maxAge(3600);
    }

    @Bean
    public WebConfig corsConfigurer() {
        return new WebConfig();
    }
}

이 부분을 넣기 전까지 계속 CORS관련 오류가 났었는데 넣고 나니 깔끔히 해결되었다.