React와 Spring으로 게시판 만들기
[React / Spring] React와 Spring 연동하기 (2)
Evolving Developer
2023. 2. 20. 09:29
React
package.json에 proxy 설정
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"proxy": "http://localhost:8080",
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
}
- scripts와 eslinConfig 사이에 "proxy": "http://localhost:8080" 코드 추가
- 앞으로 서버에 Get/Post 메서드 요청 시 자동으로 http://localhost:8080에 요청
- localhost는 내 컴퓨터의 IP 주소
App.js
import React, {useEffect, useState} from 'react';
import axios from 'axios';
function App() {
const [hello, setHello] = useState('') // hello라는 변수에 백엔드 데이터를 담을 예정
useEffect(() => {
axios.get('/api/hello') // 'http://localhost:8080/api/hello'에 GET 요청
.then(response => setHello(response.data)) // 응답을 hello라는 변수에 저장
.catch(error => console.log(error))
}, []);
return (
<div>
백엔드에서 가져온 데이터입니다 : {hello} // hello 변수 내용 출력
</div>
);
}
export default App;
Spring
TestController
@RestController
public class TestController {
@GetMapping("/api/hello") // 'http://localhost:8080/api/hello'로 GET 요청 시 아래 함수 실행
public String test() {
return "Hello, world!"; // Hello, World! 리턴
}
}