🌐 Web/React

[React + Spring Boot] Spring Boot(eclipes)와 React 연결(2)

dlalwl_jpg 2023. 4. 8. 12:50

https://studybook.tistory.com/68

 

Spring Boot(eclipes)와 React 연결(1)

1. Spring Boot 설정에서 gradle 프로젝트 생성 File > New > Spring Starter Project 를 클릭한다. 그 다음 원하는 프로젝트로 이름만 변경(나머지 변경X)한다. 나는 backend로 하였다. Next 클릭 Web에서 Spring Web 체

studybook.tistory.com

* 윗 글에 이어서 작성된 글입니다!

1. Spring boot api 서버 만들기

backend > src/main/java > com.app 우클릭을 하고 class를 클릭해 TestController를 만든다.

TestController.java를 다음과 같이 작성해준다.

package com.app;

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

 
@RestController
public class TestController {
 
    @GetMapping("/api/hello")
    public String hello(){
        return "Hello World!";
    }
}

Spring boot 로 실행을 클릭했을 때 아래 Console창처럼 나왔으면 잘 실행이 된 것이다.

그리고 아래 주소로 들어가 보면(클릭하거나 복붙해서 주소창에 입력)

http://localhost:8080/api/hello

위 화면처럼 잘 나오는 것을 볼 수 있다.


2. React 설정 변경

React로 가서 Package.json 파일을 아래와 같이 변경한다.

{
  "name": "frontend",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^16.12.0",
    "react-dom": "^16.12.0",
    "react-scripts": "^3.3.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
 
  "proxy": "http://localhost:8080",
 
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

3. Spring boot 값을 React 받아보기

react에서 App.js를 다음과 같이 변경한다.

import React, {useState, useEffect} from 'react';
import logo from './logo.svg';
import './App.css';
 
function App () {
    const [message, setMessage] = useState("");
 
    useEffect(() => {
        fetch('/api/hello')
            .then(response => response.text())
            .then(message => {
                setMessage(message);
            });
    },[])
    return (
        <div className="App">
            <header className="App-header">
                <img src={logo} className="App-logo" alt="logo"/>
                <h1 className="App-title">{message}</h1>
            </header>
            <p className="App-intro">
                To get started, edit <code>src/App.js</code> and save to reload.
            </p>
        </div>
    )
}
 
export default App;

그리고 react 실행화면을 보면 아래와 같이 spring boot의 값이 전달되어 화면에 출력되는 것을 볼 수 있다.


참고-https://sundries-in-myidea.tistory.com/71

 

Spring Boot와 React를 연동하여 개발환경을 만들어보자

이글을 읽어보기전에!! 한번 고려해볼 점을 제가 적어뒀습니다 한번 참고 해보고 프로젝트를 진행해주세요! [Java/Spring] - Spring Boot와 React를 통한 개발환경을 구성할때 고민해볼점 Spring Boot와 React

sundries-in-myidea.tistory.com