JS_fetch 사용법

dev.dave·2023년 7월 25일

Javascript

목록 보기
67/167

fetch 사용법>

프론트엔드,
리액트 js에서
다른서버에 있는 데이터를 요청할떄,
어떤식으로 받아오는지?

노드js에서
다른서버 api를 가져올떄,

fetch를 사용해 가져오는 방법이 있다.

axios 사용도 다룬다.

일단,
모질라 공식문서보면 다나온다.

일단 기본은 이 형태이고,

feetch('https://example.com/movies.json')
.then((response) => response.json())
.then((data) => console.log(data))


웹사이트 추천을 하나 하는데,
REQRES라는 사이트 이용하면,

get 은 /users
/api/users

페이징 처리는
/api/users?page=2

그냥 리퀘스트는,
/api/users/2
패스 파라미터로 나타내줌.


일단,
GET은

feetch('https://reqres.in/api/users/1')
.then((response) => response.json())
.then((data) => console.log(data))

하면 400 500 이 뜨는데,
이거는
catch로 캐칭해줘야함.

feetch('https://reqres.in/api/users/1')
.then((response) => {
//200 ~ 299 사이의 결과라면 ok가 된다.
if(!reponse.ok){
throw new Error("네크워크 응답이 올바르지 않습니다.")
}
return response.json();
})
.then((data) => console.log(data))
.catch((error) => console.log(error))

저 중간에 저렇게 작성하는게 귀찮으면,
Axios쓰면된다.
라이브러리고.


POST는,

feetch('https://reqres.in/api/users'{
method: "POST",
body: JSON.stringify({name: "noyes"}),
})
.then((res) => {
// 201 created code를 반환.
if(!res.ok){
throw new Error("네크워크 응답이 올바르지 않습니다.")
}
return res.json();
})
.then((data) => console.log(data))
.catch((error) => console.log(error))


profile
🔥개인 메모 / 다른블로그 자료 참조 / 다른블로그 자료 퍼옴 (출처표기) /여기저기서 공부 했던 내용 개인메모 & 참고 / 개인 기록 용도 블로그 입니다.🔥

0개의 댓글