본문 바로가기
부트캠프교육중/JavaScript

Fetch API

by 뭉지야 2023. 1. 19.
728x90

URL로 네트워크 요청하는 것을 가능하게 해주는 API
특정url로부터 정보를 받아오는 역할을 한다.이과정이 비동기적으로 이루어진다.

실시간정보 업데이트 위해 요청 API를 이용한다.fetch API는 요청 API중 하나이다.
fetch api는 해당정보를 원격url로부터 불러온다.

 

let url =
  "https://koreanjson.com/posts/1";
fetch(url)
  .then((response) => response.json())
  .then((json) => console.log(json))
  .catch((error) => console.log(error));

빌트인 API라 별도의 설치 필요없다.

.json() 메서드를 사용해야한다!!!!


# get 요청예시

// Promise ver
fetch('https://koreanjson.com/users/1', { method: 'GET' })
  .then((response) => response.json())
  .then((json) => console.log(json))
  .catch((error) => console.log(error));


// Async / Await ver
// async function request() {
//   const response = await fetch('https://koreanjson.com/users/1', {
//     method: 'GET',
//   });
//   const data = await response.json();
//   console.log(data);
// }

 # post 요청예시

// Promise ver
fetch('https://koreanjson.com/users', {
  method: 'POST',
  headers: {
    // JSON의 형식으로 데이터를 보내준다고 서버에게 알려주는 역할입니다.
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ nickName: 'ApeachIcetea', age: 20 }),
})
  .then((response) => response.json())
  .then((json) => console.log(json))
  .catch((error) => console.log(error));


// Async / Await ver
// async function request() {
//   const response = await fetch('https://koreanjson.com/users', {
//     method: 'POST',
//     headers: {
//       'Content-Type': 'application/json',
//     },
//     body: JSON.stringify({ nickName: 'ApeachIcetea', age: 20 }),
//   });
//   const data = await response.json();
//   console.log(data);
// }
728x90

'부트캠프교육중 > JavaScript' 카테고리의 다른 글

undefined와 null 차이  (0) 2023.01.22
Axios  (0) 2023.01.19
fs.readFile, callback함수  (0) 2023.01.18
Node.js 모듈  (0) 2023.01.18
Async , Await  (0) 2023.01.17