-
Spring Boot & React 연동하기 2카테고리 없음 2024. 3. 7. 21:38
개발 환경
1. OS : Widow
2. JDK: 17
3. IDE : Eclipse, VsCode
3. npm
Node Packaged Manager의 약자
Node.js 로 만들어진 Pakage(Module) 을 관리해주는 툴이다새로운 cmd 나 전 게시물에서 code . 을 이용해 연 Vscode 터미널에 아래 명령어를 차례대로 입력한다
3-1 npm install(package.json 파일 의존성 설치)
Package.json이란??
- 현재 프로젝트에 관한 정보와 패키지 매니저(npm, yarn)을 통해 설치한 모듈들의
의존성을 관리하는 파일이다. (메타 데이터 정보를 가지고 있다) - 확장자가 Json으로 특정 메서드를 이용해 Javascript 에서 데이터를 가져올 수 있다
- Package.json 파일이 유용한 이유는, 현재 설치되어 있는 패키지 정보를 확인할 수 있고,
다른 사람이나 다른 기기에서 내 자신에게 이 파일을 공유할 때 모든 의존성 파일들을
한 번에 다운로드 할 수 있기 때문입니다.
명령어 수행 시 아래와 같이 취약점 이슈 fix 제안 문구가 나올 수 있습니다.
npm 버전 6 이후부터 추가된 취약점 점검 기능이 실행된 것인데
npm audit fix --force를 아무리 수행해도 영원히 수정되지 않으므로 이 단계에선 넘어갑니다.
3-2 npm run-script build (배포 환경에서 사용할 파일 생성)
3-4 npm run eject (create-react-app의 종속 설정 꺼내기)
* 명령어 수행 시 아래와 같은 컨펌 메세지가 나타납니다. Y를 입력합니다.
이 메시지가 뜨면 성공 4. 파일 변경
react의 파일을 변경합니다.
4-1 appBuild path 변경
[react 프로젝트/config/paths.js 의 module.exports 에서 appBuild 라인을 'build/static'으로 변경합니다
4-2 /build/ 하위 파일 삭제
static 을 제외한 전부 삭제해줍니다.
5 Spring Boot 연동 설정
5-1 gradle 설정 추가
체크 표시 한 부분에
아래 코드를 추가합니다.
def webappDir = "$projectDir/src/main/[react 프로젝트명]" sourceSets { main { resources { srcDirs = ["$webappDir/build", "$projectDir/src/main/resources"] } } } processResources { dependsOn "buildReact" } task buildReact(type: Exec) { dependsOn "installReact" workingDir "$webappDir" inputs.dir "$webappDir" 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 installReact(type: Exec) { workingDir "$webappDir" inputs.dir "$webappDir" 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' } }
!!! 첫번째 줄의 webappDir의 경로에 frontend 프로젝트명(리액트 프로젝트 이름)을 넣습니다.
5-2 Spring Boot 테스트 소스
package my.app.test; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import jakarta.servlet.http.HttpServletRequest; @RestController @RequestMapping("/api") public class TestController { @PostMapping("/ip") public ResponseEntity<String> ip (HttpServletRequest request){ // 요청 보낸 클라이언트 ip 반환 return ResponseEntity.ok(request.getRemoteAddr()); } }
package my.app.test; 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 WebCofig implements WebMvcConfigurer{ /* * 개발환경에서의 크로스 도메인 이슈 해결을 위한 코드. 운영 배포 시 14~15행 주석 */ @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/api/**").allowCredentials(true).allowedOrigins("http://localhost:3000"); WebMvcConfigurer.super.addCorsMappings(registry); } }
5-3 react 테스트 소스 (App.js 수정)
import React, { useState, useEffect } from 'react'; import './App.css'; import customAxios from './customAxios'; function App() { // IP주소 변수 선언 const [ip, setIp] = useState(''); // IP주소 값을 설정합니다. function callback(data) { setIp(data); } // 첫번째 렌더링을 다 마친 후 실행합니다. useEffect( () => { // 클라이언트의 IP주소를 알아내는 백엔드의 함수를 호출합니다. customAxios('/ip', callback); }, [] ); return ( <div className="App"> <header className="App-header"> 이 기기의 IP주소는 {ip}입니다. </header> </div> ); } export default App;
5-4 src 아래에 customAxios.js 파일 만들기
import axios from 'axios'; // 액시오스 export default function customAxios(url, callback) { axios( { url: '/api' + url, method: 'post', /** * 개발 환경에서의 크로스 도메인 이슈를 해결하기 위한 코드로 * 운영 환경에 배포할 경우에는 15~16행을 주석 처리합니다. * * ※크로스 도메인 이슈: 브라우저에서 다른 도메인으로 URL 요청을 하는 경우 나타나는 보안문제 */ baseURL: 'http://localhost:8080', withCredentials: true, } ).then(function (response) { callback(response.data); }); }
6 . Spring Boot 프로젝트 Build
*이클립스에서 빌드 하는 방법
1.
2.
new configuration 클릭 3.
동그라미 표시 클릭 후 빌드 할 프로젝트 찾기 4. add를 클릭 해 clean build 추가 후 apply and run
이렇게 하고 기다리면........
녹색으로 도배 되면 성공!!!
실행
이렇게 하면 프로젝트 경로 밑의 /build/libs에 jar 파일이 생성되어 있을 겁니다.
이걸 직접 접근해서 실행시키면 안되드라고요
그래서 터미널로 접근해서 실행시켜보겠습니다
해당 경로로 직접 이동해서 jar 파일 이름과 경로를 확인하시고 아래에 명령어로 실행해주세요
명령어 : java -jar [jar 파일명]
*만약 axios 가 설치 되어있지 않으면 npm install axios 명령어로 다운한다
- 현재 프로젝트에 관한 정보와 패키지 매니저(npm, yarn)을 통해 설치한 모듈들의