Reactjs + Spring Boot 독립 app
@Springboot 시작시
Web 하나로 시작
model -> Integer Id, String name, String price 만들기
생성자 추가
MainController.java
@Controller
public class MainController {
private static List<Items> items = new ArrayList<Items>();
static {
items.add(new Items(1, "Apples", "$2"));
items.add(new Items(2, "Peaches", "$5"));
}
@GetMapping(value = "/items", produces = MediaType.APPLICATION_JSON_VALUE)
@CrossOrigin(origins = {"http://localhost:3000", "http://localhost:5000"})
public ResponseEntity<Object> getItems(){
Gson gson = new Gson();
String jsonInString = gson.toJson(items);
jsonInString = "{" + "\"items\" :" +jsonInString+" }";
return new ResponseEntity<Object>(jsonInString, HttpStatus.OK);
}
}
default React App 생성
App.js 파일 다음과 같이 변경
import React, { Component } from 'react';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items: []
};
}
componentDidMount() {
fetch("http://localhost:8088/items")
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
items: result.items
});
console.log(this.state.items)
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<ul>
{items.map(item => (
<li key={item.name}>
{item.name} {item.price}
</li>
))}
</ul>
);
}
}
}
export default App;