상세 컨텐츠

본문 제목

[먹로그] 스프링부트+리액트 프로젝트 생성

카테고리 없음

by yooputer 2024. 3. 3. 01:01

본문

프로젝트 기술 스택

  • Java17
  • SpringBoot3.1.9
  • Gradle
  • MyBatis
  • PostgreSQL
  • ReactJS

IntelliJ에서 프로젝트 생성


DB 연결

프로젝트 > src > resources > application.properties

DB url, username, password 입력


서버 실행 테스트

MuglogApplication.java 실행 후 웹브라우저에 http://localhost:8080으로 접속

다음과 같이 404 페이지 뜨는거 확인


리액트 설치

cmd에서 프로젝트/src/main으로 이동

npx create-react-app frontend 명령어 실행

 

frontend 디렉토리 생성된거 확인


리액트 실행

cmd에서 프로젝트/src/main으로 이동

npx start 명령어 실행

웹브라우저에 http://localhost:3000으로 접속


프록시 설정

cmd에서 프로젝트/src/main으로 이동

npm install http-proxy-middleware --save 명령어 실행

 

프로젝트 > src > main > frontend > src에 setupProxy.js 파일 생성

아래 코드 입력

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

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

Axios 설치

cmd에서 프로젝트/src/main/frontend로 이동

npm install axios --save 명령어 실행


리액트-스프링부트 연결 테스트

프로젝트 > src > main > java > com > muglog

 

controller 패키지 생성

 

프로젝트 > src > main > java > com > muglog > controller

TestController 클래스 생성

getChar 메서드 구현

@RestController
public class TestController {
    @GetMapping("/api/test/getChar")
    private String getChar(@RequestParam(required = false, defaultValue = "0") Integer index){
        String hello = "안녕하세요";

        return String.valueOf(hello.charAt(index));
    }
}

 

프로젝트 > src > main > frontend > app.js

app.js 내용 수정

import {useEffect, useState} from "react";
import axios from "axios";

let index = 0;

function App() {
  const [char, setChar] = useState('');

  useEffect(() => {
    axios.get('/api/test/getChar')
        .then((res) => {
          setChar(res.data);
        })
  }, []);
  return (
      <div className="App">
        <button onClick={ ()=> {
            axios.get('/api/test/getChar', {params: {index: index}})
                .then((res) => {
                    setChar(res.data);
                    index = index > 5 ?  0 : index+1;
                })
                .catch(() => console.log('요청 실패'))}
        }>인사</button>
        <p>{ char }</p>
      </div>
  );
}

export default App;

 

테스트 결과


참고자료

https://velog.io/@ung6860/React-Spring-%ED%94%84%EB%A1%9C%EC%A0%9D%ED%8A%B8-%EC%83%9D%EC%84%B1

 

[React + Spring] 프로젝트 연동

React + Spring Boot 프로젝트를 생성하고 연동 후 배포까지 해보자.

velog.io