[Spring] 리액트 스프링 연결

손시연·2022년 7월 13일
0

project

목록 보기
1/11
post-thumbnail

1. [Spring] 생성

https://start.spring.io/


2. [리액트] 설치

>> cd src/main
>> npx create-react-app frontend	# npx create-reeact {프로젝트명}


3. [리액트] 실행

>> cd frontend	# cd {프로젝트명}
>> npm start


4. [리액트] Proxy 설정

  • CORS (Cross Origin Resource Sharing)

    서버와 클라이언트가 동일한 IP주소에서 동작하고 있다면, resource를 제약 없이 서로 공유할 수 있지만, 만약 다른 도메인에 있다면 원칙적으로 어떤 데이터도 주고받을 수 없음
  • 리액트는 localhost:3000 으로, 스프링은 localhost:8080 으로 동작함. 서로 다른 도메인을 사용하고 있으므로 CORS 관련 이슈가 발생함. 따라서 proxy를 설정함으로 같은 도메인(localhost:8080)을 사용하도록 함
    • 스프링보다 리액트에서 설정하는 것이 더 간단함
  • src/main/frontend 폴더에서 Proxy 관련 모듈 설치
>> npm install http-proxy-middleware --save
  • ✔️방법1 : package.json"proxy": "http://localhost:8080"을 입력
  • 방법2 :src/main/frontend/src 폴더에서 setProxy.js 파일을 생성하고, 아래의 코드를 작성함
    • 프론트엔드에서 /api로 요청을 보내면, 백엔드인 8080포트(=target)로 요청이 도착하게 됨.
const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'http://localhost:8080',	# 서버 URL or localhost:설정한포트번호
      changeOrigin: true,
    })
  );
};
  • 추가) [Spring] 연결 포트 변경 방법

    application.properties 에 다음과 같이 입력하면 localhost:8081로 열림
server.port = 8081

5. [리액트] fetch()를 이용한 서버 통신

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

function App() {
  const [message, setMessage]=useState([]);
  useEffect(()=>{
    fetch("/api/demo-web")
        .then((response)=>{
          return response.json();
        })
        .then((data)=>{
            setMessage(data);
        });
  },[]);
  return (
    <div>
        {message}
    </div>
  );
}

export default App;

6. [Spring] Controller 생성

@RestController
public class HelloController {
    @GetMapping("/api/demo-web")
    public List<String> Hello(){
        return Arrays.asList("리액트 스프링 ", "연결 성공");
    }
}


7. localhost:3000 으로 실행

  • 스프링 부트 실행 + 리액트 실행(npm start)

8. [Spring] build.gradle 수정

  • build.gradle 에 추가
    • SpringBoot 프로젝트와 React 프로젝트가 하나의 패키지가 될 수 있는 빌드 구성
    • SpringBoot 프로젝트가 빌드될 때 React 프로젝트가 먼저 빌드되고, 결과물을 SpringBoot 프로젝트 빌드 결과물에 포함시킨다는 내용
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"
}

9. localhost:8080 으로 실행

>> cd C:\demo-web

>> .\gradlew build

>> cd build/libs
>> dir

>> java -jar demo-web-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#1-spring-boot
https://kth990303.tistory.com/210

profile
Server Engineer

4개의 댓글

comment-user-thumbnail
2022년 9월 5일

감사합니다~ 제이쿼리로 만든 게시판을 리액트로 바꿔만드는것도 괜찮을거 같네요^^ 꽤 의미있는 공사가 될거 같아요 ㅋㅋ

1개의 답글
comment-user-thumbnail
2023년 11월 6일

감사합니다 ㅎㅎ 글이 잘 정리 되어있어서 보기 좋아요!!

1개의 답글