프로젝트 > 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,
})
);
};
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