나의 공부기록

[React + Spring] 01. react와 Spring 연동 본문

프로그래밍/React(리액트)

[React + Spring] 01. react와 Spring 연동

나의 개발자 2023. 6. 28. 16:19

🎃사용환경🎃

IDE : Intellij IDEA 2021.3.3
Database : PostgreSQL
Language : Spring Boot & React

 

1️⃣ Spring 프로젝트 생성

Spring 프로젝트 생성 설정
Spring boot 의존성 설정

 

2️⃣ Spring Controller 만들기

package com.bhchoi.reactspring.Controller;

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

import java.util.Arrays;
import java.util.List;

@RestController
public class HelloWorldController {

    @GetMapping("hello")
    public List<String> hello(){
        return Arrays.asList("안녕하세요","hello","hi");
    }
}

Spring 서버 실행 결과

 

3️⃣React 프로젝트 만들기

npx create-react-app frontend //프로젝트명

파일 구조

react 프로젝트를 생성하면 해당 프로젝트명 아래 node_modules파일과 public, src 파일 등이 생성됩니다. 해당 프로젝트를 시작하려면 npm start를 하면 됩니다.

단, 해당 react 프로젝트 경로로 이동하여 npm start를 해야 합니다.

react 프로젝트 첫 실행 화면

4️⃣React 화면에 Spring 데이터 출력하기

import './App.css';
import {useEffect, useState} from "react";

function App() {

  const [message, setMessage] = useState([]);

  useEffect(()=>{
    fetch("/hello")
        .then((response)=>{
          return response.json();
        })
        .then((data)=>{
            setMessage(data);
        });
  }, []);

  return (
    <div className="App">
      <header className="App-header">
        <ul>
            {message.map((contents, idx)=><li key={`${idx} - ${contents}`}>{contents}</li>)}
        </ul>
      </header>
    </div>
  );
}

export default App;

실행 결과(React 화면)