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! 리턴
}
}
결과
'React와 Spring으로 게시판 만들기' 카테고리의 다른 글
[Springboot] Spring Data JPA 소개 - ORM과 JPA (0) | 2023.03.04 |
---|---|
[React] Route로 페이지 이동하기 (5) - 글쓰기 버튼 클릭 시 페이지 이동 (0) | 2023.03.04 |
[React] 게시판 디자인하기 (4) - 글쓰기 버튼 만들기 (0) | 2023.03.03 |
[React] 게시판 디자인하기 (3) (0) | 2023.02.24 |
[React] 리액트 프로젝트 시작하기 (1) (0) | 2023.02.20 |