각각 생성된 스프링부트와 리액트 프로젝트를 연동하는 과정입니다.
데이터로 사용할 객체 생성 후, 리액트에서 요청 받을 컨트롤러 설정
@Getter public static class User 23; int id; String username; String passwd; String email; public User(int id, String username, String passwd, String email) 23; this.id = id; this.username = username; this.passwd = passwd; this.email = email; 25; 25;
@RestController public class HiReactController 23; // 리액트와 연결될 주소 매핑 @PostMapping("/api/users") public User user() 23; System.out.println("::: HiReactController IN :::"); User user = new User(1, "eleven", "1234", "jskim@repia.com"); return user; 25; 25;
부트와 통신하기 위해 proxy와 axios 라이브러리 설치
PS ~\react-app> npm install http-proxy-middleware --save PS ~\react-app> npm install axios --save
프록시 설정을 위해 src/setupProxy.js 파일 생성
const 23;createProxyMiddleware25; = require("http-proxy-middleware"); module.exports = function(app)23; app.use( "/api" , createProxyMiddleware(23; target: "http://localhost:8006" // 부트프로젝트 주소 , changeOrigin: true 25;) ); 25;;
axios가 요청을 보내고, 리턴값을 화면에 띄우기 위해 src/App.js 파일 수정
import logo from './logo.svg'; import React, 23;useState, useEffect25; from "react"; import './App.css'; import Axios from "axios"; function App() 23; const [user, setUser] = useState(""); useEffect(() => 23; Axios.post("/api/users").then((response) => 23; if(response.data)23; console.log("console check! ===> ", response.data); setUser(response.data); 25; else 23; alert("failed to"); 25; 25;); 25;, []); return ( <div className="App"> <header className="App-header"> <img src=23;logo25; className="App-logo" alt="logo" /> <h1>Hello, React!</h1> <p>No.23;user.id25;</p> <p>name is 23;user.username25;</p> <p>password? 23;user.passwd25;</p> <p>email... 23;user.email25;</p> <a className="App-link" href="https://reactjs.org" target="_blank" rel="noopener noreferrer" > Learn React </a> </header> </div> ); 25; export default App;
스프링부트 서버 실행 후, 리액트 실행하여 화면 확인
PS ~\react-app> npm run start