Spring
HelloController.java
package com.sto.salepurchase.backstosalepurchase;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Arrays;
import java.util.List;
@RestController
public class HelloController {
@GetMapping("hello")
public List<String> Hello(){
return Arrays.asList("์๋ฒ ํฌํธ๋ 8080", "๋ฆฌ์กํธ ํฌํธ๋ 3000");
}
}
main method ์คํ
localhost:8080/hello ์ ์ ํ ํ์ธํ๊ธฐ
React
SpringBoot Controller์ ์ฐ๋ํ๊ธฐ ์ํ proxy ์ค์
react : 3000 port
SpringBoot : 8080 port๋ก ์คํ๋๊ธฐ ๋๋ฌธ์ CORS ๋ฌธ์ ํด๊ฒฐ์ ์ํ proxy ์ค์ ์ด ํ์
package.json
"proxy": "http://localhost:8080"
App.js
import React, { useState, useEffect } from "react";
App.js > App
const [message, setMessage] = useState([]);
useEffect(() => {
fetch("/hello")
.then((res) => {
return res.json();
})
.then((data) => {
setMessage(data);
});
}, []);
Fetch : http ํด๋ผ์ด์ธํธ. ๋น๋๊ธฐ ํต์ ๊ธฐ์ . ์๋ฐ์คํฌ๋ฆฝํธ์ built in API
axios์ ๊ฒฝ์ฐ ์๋์ผ๋ก jsonํ์์ผ๋ก ๋ณํํ๋ ๋ฐ๋ฉด .json() ๋ฉ์๋ ์ฌ์ฉํด์ผ ํจ.
fetch(resource)
fetch(resource, options)
options ์๋ต ์ get๋ฐฉ์
App.js > App return
<ul>
{message.map((v, idx) => (
<li key={`${idx}-${v}`}>{v}</li>
))}
</ul>
App.js ์ ์ฒด ์ฝ๋
import logo from "./logo.svg";
import "./App.css";
import React, { useState, useEffect } from "react";
function App() {
const [message, setMessage] = useState([]);
useEffect(() => {
fetch("/hello")
.then((res) => {
return res.json();
})
.then((data) => {
setMessage(data);
});
}, []);
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
<ul>
{message.map((v, idx) => (
<li key={`${idx}-${v}`}>{v}</li>
))}
</ul>
</header>
</div>
);
}
export default App;
๋ ํ๋ก์ ํธ ๋ชจ๋ ์คํ ํ localhost:3000 ์ ์
์ฐธ๊ณ :
https://7942yongdae.tistory.com/136
https://kth990303.tistory.com/210
axios, fetch
https://koras02.tistory.com/48
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API