26 Haziran 2020 Cuma

fetch metodu - ES6

Giriş
Fetch'e gelmeden önce sırayla şunlar kullanılıyordu. Fetch ise tarayıcıda yerleşik bir kütüphane
XMLHttpRequest -> JQuery.ajax -> Axios veya Request (npm) -> Fetch
fetch API Nedir?
Açıklaması şöyle.
The Fetch API was introduced in relatively newer versions of JavaScript and has built-in support for Promises. Technically, it is just another method of hitting HTTP Requests while harnessing the powers and perks of Promises and Promise Chaining.

So in the fetch API, you pass the arguments in the following order:
- URL
- { } (This is purely optional, used to customize our Request)

The fetch API simply returns a Promise and hence we can implement handlers to process the response from the Promise. Based on whether the Promise resolves or rejects, we can handle that with JavaScript's  then() method. 
ES6 ile geliyor. Açıklaması şöyle
As of today, there are two primary ways to make a request in the browser. XMLHttpRequest and fetch. XMLHttpRequest existed in browsers for a long time. the fetch was introduced with ES6.
fetch ve window.fetch Aynı Şeydir
Açıklaması şöyle
On your developer console, try this experiment:
fetch === window.fetch
You'll see that this returns true. They are in fact the same thing.

window is the global object in a browser context. The browser APIs (distinct from language features) are found on the global window object.
Örnek - GET
Açıklaması şöyle.
fetch accepts AbortSignal as part of the second argument.
Şöyle yaparız. Burada fetch(...).then(...).catch(...) şeklinde kullanılıyor
const controller = new AbortController();
const signal = controller.signal;


// API responds after 5s
// Note the 'signal' in the second argument
fetch('https://slowmo.glitch.me/5000', { signal })
  .then(r => r.json())
  .then(response => console.log(response))
  .catch(err => {
    if (err.name === 'AbortError') {
      console.log('Fetch was aborted');
    } else {
      console.error('Oops!', err);
    }
  });

// Abort the request after 2s
// This will abort the fetch with 'AbortError'
setTimeout(() => {
  controller.abort();
}, 2000);
Örnek - POST JSON
Post için şöyle yaparız. Post için timeout vermenin yolu yok.
fetch('<url_here>', {
  body: JSON.stringify(data),
  headers: {
    'content-type': 'application/json' 
  },
  method: 'POST'
})
  .then(response => response.json())
  .then(res => {
    //work with response data
});
Örnek - POST JSON
Şöyle yaparız
const response = await fetch('/api/getMarkers', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: JSON.stringify(num) // body data type must match "Content-Type" header
  });
mark = await response.json();
this.setState({ markers: mark })

Hiç yorum yok:

Yorum Gönder