Spring Boot에서 간단하게 만들었던 controller를 가지고 axios를 이해해보자.
먼저, 과거 만들었던 Spring Boot 부분
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
package mul.cam.a.controller;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import mul.cam.a.dto.HumanDto;
@RestController
// MVC model에서의 @Controller(controller부분) + @Responsebody(ajax부분)
public class HelloController {
/////////////// 서버(back-end)에서 값을 보내주기만 하는 부분 ////////////////////////
// http://localhost:3000/
@RequestMapping(value = "/", method = RequestMethod.GET)
public String hello() {
System.out.println("HelloController hello() " + new Date());
return "hello"; // ajax를 통해 값을 front-end로 보내준다.
}
// http://localhost:3000/test
@GetMapping(value = "/test")
public String test() {
System.out.println("HelloController test() " + new Date());
return "테스트";
}
// http://localhost:3000/human
@GetMapping(value = "/human")
public HumanDto getDto() {
System.out.println("HelloController getDto() " + new Date());
HumanDto human = new HumanDto(1001, "홍길동", "서울시");
return human;
}
// http://localhost:3000/get_list
@GetMapping("/get_list")
public List<HumanDto> get_list(){
System.out.println("HelloController get_list() " + new Date());
List<HumanDto> list = new ArrayList<>();
list.add(new HumanDto(101, "홍길동", "서울시"));
list.add(new HumanDto(102, "성춘향", "남원시"));
list.add(new HumanDto(103, "임꺽정", "광주시"));
return list;
}
////////////////// 외부에서 데이터를 서버로 보낸 경우, 서버에서 매개변수로 받는 것 /////////////////////
// 예를 들어, http://localhost:3000/conn_param?title=제목입니다
@GetMapping(value = "/conn_param")
public String conn_param(String title) {
System.out.println("HelloController conn_param() " + new Date());
System.out.println("title: " + title);
return "conn success";
}
// http://localhost:3000/param_obj?number=1002&name=성춘향&address=남원시
@GetMapping(value = "param_obj")
public String param_obj(HumanDto human) {
System.out.println("HelloController param_obj() " + new Date());
System.out.println("human: " + human);
return "OK";
}
}
|
cs |
axios는 ajax를 대신!!
react에서 axios를 사용하기 위해서는 npm install axios를 실행해줘야 한다.
또한, import axios from 'axios'와 같이 import 해줘야 한다.
현재 spring boot에서 port number 3000을 사용하고 있으므로, 겹치지 않도록 react의 port number를 미리 변경해주도록 한다.
바꾸는 방법은 package.json 파일에서
와 같이 set PORT=포트넘버 && 을 기존 코드 앞에 추가해주면 된다.
Spring Boot의 각 Mapping의 value를 기준으로 나눠서 살펴보자.
1. /test
Spring Boot 부분
1
2
3
4
5
6
7
|
// http://localhost:3000/test
@GetMapping(value = "/test")
public String test() {
System.out.println("HelloController test() " + new Date());
return "테스트";
}
|
cs |
React 부분
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
import React, {useEffect, useState} from "react";
import axios from 'axios';
function App(){
const fetchData = async () => {
const response = await axios.get('http://localhost:3000/test', {} )
console.log(response.data);
}
useEffect(()=>{
fetchData();
}, []);
return(
<div>
<p>axios</p>
</div>
)
}
export default App;
|
cs |
결과
2. /human
Spring Boot 부분
1
2
3
4
5
6
7
8
9
|
// http://localhost:3000/human
@GetMapping(value = "/human")
public HumanDto getDto() {
System.out.println("HelloController getDto() " + new Date());
HumanDto human = new HumanDto(1001, "홍길동", "서울시");
return human;
}
|
cs |
React 부분
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
import React, {useEffect, useState} from "react";
import axios from 'axios';
function App(){
const fetchData = async () => {
const response = await axios.get('http://localhost:3000/human', {} )
console.log(response.data);
}
useEffect(()=>{
fetchData();
}, []);
return(
<div>
<p>axios</p>
</div>
)
}
export default App;
|
cs |
결과
3. /conn_param
1,2번과 다르게 front-end(react)에서 back-end(spring boot)로 값을 넘겨주고, 다시 넘겨받는 구조이다.
즉,
const response = await axios.get('http://localhost:3000/test', {} ) // 1번
const response = await axios.get('http://localhost:3000/human', {} ) // 2번
에서는 { } 처럼 넘겨주는 값이 없어서 비어있지만,
3번에서는
const response = await axios.get('http://localhost:3000/conn_param', { params: {title:"제목"} } ) 와 같이
{ params: {title:"제목"} }으로 값을 넘겨준다.
이때, title은 매개변수명이므로 spring boot에서의 매개변수명과 맞춰줘야 한다.
Spring Boot 부분
1
2
3
4
5
6
7
8
9
|
// 예를 들어, http://localhost:3000/conn_param?title=제목입니다
@GetMapping(value = "/conn_param")
public String conn_param(String title) {
System.out.println("HelloController conn_param() " + new Date());
System.out.println("title: " + title);
return "conn success";
}
|
cs |
React 부분
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
import React, {useEffect, useState} from "react";
import axios from 'axios';
function App(){
const fetchData = async () => {
const response = await axios.get('http://localhost:3000/conn_param', { params: {title:"제목"} } )
console.log(response.data);
}
useEffect(()=>{
fetchData();
}, []);
return(
<div>
<p>axios</p>
</div>
)
}
export default App;
|
cs |
결과
이제 post 방식으로도 axios를 사용해보자.
먼저, Spring Boot 부분은 아래와 같다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
package mul.cam.a.controller;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import mul.cam.a.dto.MemberDto;
import mul.cam.a.service.MemberService;
@RestController
public class MemberController {
@Autowired
MemberService service;
@PostMapping(value = "/allList")
public List<MemberDto> allList(String user){
System.out.println("MemberController allList " + new Date());
System.out.println("user: " + user);
return service.allMember();
}
}
|
cs |
React 부분
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
import React, {useEffect, useState} from "react";
import axios from 'axios';
function App(){
const [memberlist, setMemberlist] = useState([]);
// post는 매개변수가 다르다
// get방식은 2번째 위치에 params가 들어오고,
// post 방식은 2번째 위치에는 null, 3번째 위치에 params가 들어온다.
const fetchData = async () => {
const response = await axios.post('http://localhost:3000/allList', null, { params: {user:"홍길동"} });
console.log(response.data);
setMemberlist(response.data);
}
useEffect(()=>{
fetchData();
}, []);
return(
<div>
<h3>axios test</h3>
<table border="1">
<thead>
<tr>
<th>No</th><th>id</th><th>password</th><th>name</th><th>email</th>
</tr>
</thead>
<tbody>
{
memberlist.map(function(member, i){
return (
<tr key={i}>
<th>{i+1}</th>
<td>{member.id}</td>
<td>{member.pwd}</td>
<td>{member.name}</td>
<td>{member.email}</td>
</tr>
)
})
}
</tbody>
</table>
</div>
)
}
export default App;
|
cs |
결과를 보기에 앞서, db에 이미 저장했던 값들이 있어서 아래와 같이 결과가 나타나는 것뿐이지 table 안의 값들은 큰 의미가 없다.
이때, react 코드를 아래와 같이 작성할 수도 있다.(table 부분)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
import React, {useEffect, useState} from "react";
import axios from 'axios';
function App(){
const [memberlist, setMemberlist] = useState([]);
// post는 매개변수가 다르다
// get방식은 2번째 위치에 params가 들어오고,
// post 방식은 2번째 위치에는 null, 3번째 위치에 params가 들어온다.
const fetchData = async () => {
const response = await axios.post('http://localhost:3000/allList', null, { params: {user:"홍길동"} });
console.log(response.data);
setMemberlist(response.data);
}
useEffect(()=>{
fetchData();
}, []);
return(
<div>
<h3>axios test</h3>
<table border="1">
<thead>
<tr>
<th>No</th><th>id</th><th>password</th><th>name</th><th>email</th>
</tr>
</thead>
<tbody>
{
memberlist.map(function(member, i){
return (
// <tr key={i}>
// <th>{i+1}</th>
// <td>{member.id}</td>
// <td>{member.pwd}</td>
// <td>{member.name}</td>
// <td>{member.email}</td>
// </tr>
<TableRow cnt={i + 1} mem={member} key={i} />
)
})
}
</tbody>
</table>
</div>
);
}
function TableRow(props){
return(
<tr>
<th>{props.cnt}</th>
<td>{props.mem.id}</td>
<td>{props.mem.pwd}</td>
<td>{props.mem.name}</td>
<td>{props.mem.email}</td>
</tr>
);
}
export default App;
|
cs |
끝.
'React' 카테고리의 다른 글
[React] file upload & download (0) | 2023.03.30 |
---|---|
[React] session과 cookie (0) | 2023.03.29 |
[React] hook - useEffect (0) | 2023.03.29 |
[React] hook - useState (0) | 2023.03.29 |
[React] 리액트 시작 및 기초 (0) | 2023.03.29 |