사용자 도구

사이트 도구


wiki:javascript:react:springboot_react

SpringBoot + React

각각 생성된 스프링부트와 리액트 프로젝트를 연동하는 과정입니다.

  • 스프링부트 IDE : STS4
  • 리액트 IDE : VSCode

SpringBoot

데이터로 사용할 객체 생성 후, 리액트에서 요청 받을 컨트롤러 설정
@Getter
public static class User
{
	int id;
	String username;
	String passwd;
	String email;
 
	public User(int id, String username, String passwd, String email)
	{
		this.id = id;
		this.username = username;
		this.passwd = passwd;
		this.email = email;
	}
}
@RestController
public class HiReactController
{	
	// 리액트와 연결될 주소 매핑
	@PostMapping("/api/users")
	public User user()
	{
		System.out.println("::: HiReactController IN :::");
		User user = new User(1, "eleven", "1234", "jskim@repia.com");
 
		return user;
	}
}


React

부트와 통신하기 위해 proxy와 axios 라이브러리 설치
PS ~\react-app> npm install http-proxy-middleware --save
PS ~\react-app> npm install axios --save


프록시 설정을 위해 src/setupProxy.js 파일 생성
const {createProxyMiddleware} = require("http-proxy-middleware");
 
module.exports = function(app){
    app.use(
        "/api"
        , createProxyMiddleware({
            target: "http://localhost:8006" // 부트프로젝트 주소
            , changeOrigin: true
        })
    );
};


axios가 요청을 보내고, 리턴값을 화면에 띄우기 위해 src/App.js 파일 수정
import logo from './logo.svg';
 
import React, {useState, useEffect} from "react";
import './App.css';
import Axios from "axios";
 
 
function App()
{
  const [user, setUser] = useState("");
  useEffect(() => {
    Axios.post("/api/users").then((response) => {
      if(response.data){
        console.log("console check! ===> ", response.data);
        setUser(response.data);
      }
      else
      {
        alert("failed to");
      }
    });
  }, []);
 
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
 
        <h1>Hello, React!</h1>
 
        <p>No.{user.id}</p>
        <p>name is {user.username}</p>
        <p>password? {user.passwd}</p>
        <p>email... {user.email}</p>
        <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" >
          Learn React
        </a>
 
      </header>
    </div>
  );
}
 
export default App;


스프링부트 서버 실행 후, 리액트 실행하여 화면 확인
PS ~\react-app> npm run start

Ref

/var/services/web/dokuwiki/data/pages/wiki/javascript/react/springboot_react.txt · 마지막으로 수정됨: 2023/01/13 18:44 (바깥 편집)