FETCH API
- fetch artinya mengambil. metode fetch bisa jadi alternatif untuk ajax
- perbedaan XMLHttpRequest dengan JQuery adalah
1. fetch bisa mengembalikan sebuah promise
2. secara bawaan(default), fetch tidak akan menerima cookie dari server server
3. fetch dapat digunakan di web browser dan juga nodeJs dengan modul node-fetch
- fungsi then, catch, response
fetch("https://api.example.com/data")
.then((response) => {
// response
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json; // if true response atau jika benar diresponse
})
.then((data) => {
console.log(data); // melakukan sesuatu dengan data yang diterima
})
.catch((error) => {
console.error("there was a problem with the fetch operation", error);
});
- respsonse berisi response HTTP dari permintaan yang anda lakukan
- object respons memilki banyak format tertentu
1. response.text()
2. response.json()
3. response.formData()
4. response.blob()
- anda juga dapat memeriksa status HTTP header, body dari response seperti status OK
- pemanggilan
.fetch() adalah metode yang digunakan pada object
.catch() adalah metode yang digunakan untuk menangani kesalaha
mengatur beberapa opsi fetch
fetch("http://example.com/movies/.json")
.then(function (response) {
return response.json;
})
.then(function (myJson) {
console.log(JSON.stringify(myJson));
});
fetch(url, {
method: "POST", // GET, POST, PUT, DELETE, etc
mode: "cors", // no-cors, cors, *same-origin
chace: "no-chache", // *default, no-chache, reload, force-chace, only-if-chaced
credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-type": "application/json",
"Content-type": "application/x-www-form-urlencoded",
},
redirect: "follow", // manual, *follow, error
referrer: "no-referrer", // no-referrer, *client
body: JSON.stringify(data), // body data type must match "Content-type" header
}).then((response) => response.json()); // parser JSON response into native javascript object