React
[React] fetch()로 restful API 구현
hiolivia
2022. 5. 20. 10:57
리액트에서 자바스크립트 메소드인 fetch()를 사용해 resful API를 구현해볼텐데요, fetch의 사용법은 다음과 같습니다.
fetch(url, {options})
//url: api 통신을 위해 접근할 url
//options: 매개변수, method를 지정
options에는 request (요청), response(응답)의 인터페이스가 들어갑니다.
request
- method
method는 우리가 알고 있는 HTTP method가 들어가는데요, 다음의 형식을 따릅니다.
C : POST
R : GET
U : PUT
D: DELETE
- header
header에는 request header를 지정해줍니다.
ex) "Content-Type": "application/json"
- body
body에는 전송할 데이터를 넣어주는데, 객체 타입으로 들어갑니다.
예제1 ) POST
- 영단어장에 새로운 단어 등록하기
fetch(`http://localhost:3001/words`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
day: day.current.value,
eng: eng.current.value,
kor: kor.current.value,
isDone: false,
}),
}).then((res) => {
if (res.ok) {
alert("저장이 완료되었습니다.");
navigate(`/list/${day.current.value}`);
}
});
요청을 날렸을 때 응답으로 ok, 즉 true를 반환한다면 alert 창을 띄우고, navigate를 사용해 링크를 이동시킵니다.
예제2 ) GET
- 영단어장 가져오기
fetch("http://localhost:3001/words")
.then((val) => {
return val.json();
})
.then((data) => console.log(data));
데이터를 json 형식으로 파싱해준 다음 사용합니다.
예제3) PUT
- 단어 수정하기
fetch(`http://localhost:3001/words/${props.word.id}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
...props.word,
isDone: !done,
}),
}).then((res) => {
if (res.ok) {
setDone(!done);
}
});
해당 단어 학습 완료 시 완료 체크를 하면 상태 수정이 됩니다. props로 전달받은 state의 값을 변경해주기 위해 props.word를 복사해준 다음, isDone을 수정해주었습니다.
예제4) DELETE
- 단어 삭제하기
fetch(`http://localhost:3001/words/${props.word.id}`, {
method: "DELETE",
}).then((res) => {
if (res.ok) {
setDel({ id: 0 });
}
});
DELETE에는 전송할 데이터가 없기 때문에 body가 필요없습니다.
이렇게 fetch를 이용해 restful API를 구현할 수 있었습니다!