fetch란?
클라이언트에서 직접 API를 호출해주는것
(브라우저에서 직접 비동기 http통신을 하는것을 Ajax라고 불렸었다.)
브라우저에 내장된 함수로 예전에는 requrest,axios,jQuery같은 라이브러리를 사용해 API를 호출했다.
즉, 프론트엔드에서 백엔드에 요청할때 쓰인다!
fetch사용법
fetch(url, options)
.then((response) => console.log("response:", response))
.catch((error) => console.log("error:", error));
첫번째 인자로 URL을 두번쨰 인자로 옵션을 객체로 받는다.
Promise객체를 리턴하기 때문에 비동기적으로 실행된다.
GET요청
fetch("localhost:3000/api/user")
.then((response) =>console.log(response));
api/user경로로 요청을 보내는 형태이다.
localhost:3000은 생략이 가능하다.
Response {status: 200, ok: true, redirected: false, type: "cors", url: "localhost:3000/api/user", …}
위와 같은 형태로 응답이 전달된다.
대부분의 REST API들은 JSON 형태의 데이터를 응답하기 때문에, 응답(response) 객체는 json() 메서드를 제공한다.
fetch("localhost:3000/api/user")
.then((response) => response.json())
.then((data) => console.log(data));
따라서 위와 같이 호출하게 되면
{//예시입니다.
"loginId": "id",
"password": "1234"
}
이러한 응답을 얻을 수 있다.
GET은 특정 API에 저장된 데이터를 보여줄때 주로 사용된다.
POST요청
데이터를 생성해야할 때 주로 사용된다.
fetch("localhost:3000/api/user", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
loginId: "id",
password: "1234",
}),
}).then((response) => console.log(response));
method 옵션을 POST로 지정하고, headers 옵션을 통해 JSON 포멧을 사용한다고 알려준다.
Response {type: "cors", url: "localhost:3000/api/user", redirected: false, status: 201, ok: true, …}
위와 같은 형식으로 응답이 오게 된다.
fetch("localhost:3000/api/user", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
loginId: "id",
password: "1234",
}),
})
.then((response) => response.json())
.then((data) => console.log(data));
다시한번 json메소드를 호출하면 응답을 아래와 같이 얻을 수 있다.
{loginId: "id", password: "1234"}
PUT 요청
PUT은 method만 PUT으로 바뀌고 POST와 방식이 동일하다.
fetch("localhost:3000/api/user", {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
loginId: "id",
password: "1234",
}),
})
.then((response) => response.json())
.then((data) => console.log(data));
PUT에서도 이와 같이 응답이 온다.
{loginId: "id", password: "1234"}
DELETE 요청
fetch("localhost:3000/api/user", {
method: "DELETE",
})
.then((response) => response.json())
.then((data) => console.log(data));
DELETE 방식은 보낼 데이터가 없기 떄문에 headers와 body옵션이 필요하지 않다.
+express router의 코드
router.get('/api/user', (req, res, next) => {
res.json({ title: data });
})
fetch가 보내는 GET요청을 express router에서 위와 같이 받을 수 있다.
+ POST,PUT,DELETE도 메소드만 바뀌고 동일하다.
반응형
SMALL
'웹 프로그래밍 > FrontEnd' 카테고리의 다른 글
[React] useRef는 unmount 되어도 유지될까? (0) | 2023.03.10 |
---|---|
[React] useState? useRef? (feat.단축키 추가) (0) | 2023.01.29 |
[JavaScript] Bind가 뭐죠? (0) | 2021.09.15 |
이벤트 버블링, 캡쳐, 위임 (0) | 2021.09.10 |