본문 바로가기
JS

Fetch API

by kicksky 2021. 3. 5.

보통 axios를 쓰지만 그래도 fetch를 쓴다면

 

const response = await fetch( url )

 

response 객체

프로퍼티

- headers

- ok ( 200 - 299 사이면 true )

- status

- statusText

- redirected ...

- body

메서드

- json( )

...

// Function to do an Ajax call
const doAjax = async () => {
  const response = await fetch('Ajax.php'); // Generate the Response object
  if (response.ok) {
    const jsonValue = await response.json(); // Get JSON value from the response body
    return Promise.resolve(jsonValue);
  } else {
    return Promise.reject('*** PHP file not found');
  }
}

// Call the function and output value or error message to console
doAjax().then(console.log).catch(console.log);

- ok로 통신 성공 여부 확인한 뒤,

- json( ) 메소드로 데이터를 json 형식으로 바꾸고

- 프로미스를 반환 → thenable

 

#1 POST

let fetchData = {
  method: 'POST',
  body: data,
  headers: new Headers()
}

fetch(url, fetchData)
.then(function() {
    // Handle response you get from the server
});

혹은

const url = 'https://randomuser.me/api';

let data = {
  name: 'Sara'
}

var request = new Request(url, {
    method: 'POST',
    body: data,
    headers: new Headers()
});

#2 POST (2015)

체이닝

function status(response) {
  if (response.status >= 200 && response.status < 300) {
    return Promise.resolve(response)
  } else {
    return Promise.reject(new Error(response.statusText))
  }
}

function json(response) {
  return response.json()
}

fetch('users.json')
  .then(status)
  .then(json)
  .then(function(data) {
    console.log('Request succeeded with JSON response', data);
  }).catch(function(error) {
    console.log('Request failed', error);
  });
fetch(url, {
    method: 'post',
    headers: {
      "Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
    },
    body: 'foo=bar&lorem=ipsum'
  })
  .then(json)
  .then(function (data) {
    console.log('Request succeeded with JSON response', data);
  })
  .catch(function (error) {
    console.log('Request failed', error);
  });

www.digitalocean.com/community/tutorials/how-to-use-the-javascript-fetch-api-to-get-data

developer.mozilla.org/en-US/docs/Web/API/Response

'JS' 카테고리의 다른 글

배열 Array: 루프  (0) 2021.03.08
중첩된 async await  (0) 2021.03.08
Array-like objects, NodeList, HTMLCollection  (0) 2021.03.04
배열 Array: 아이템 추가 및 삭제, flat( )  (0) 2021.03.03
Intersetion Observer API  (0) 2021.03.01

댓글