[[oktatas:web:javascript:javascript_fetch|< JavaScript fetch]] ====== JavaScript - A fetch ====== * **Szerző:** Sallai András * Copyright (c) 2024, Sallai András * Licenc: [[https://creativecommons.org/licenses/by-sa/4.0/|CC Attribution-Share Alike 4.0 International]] * Web: https://szit.hu ===== A fetch() ===== A fetch() az ES6-ban került a JavaScript-be. A fetch megjelenése előtt a XMLHttpRequest (XHR) API állt rendelkezésre. A használata azonban nehézkes, nem könnyen olvasható kódot eredményez. ===== A fetch paraméterei ===== fetch(url, {options}) fetch(url, {method: "GET") fetch(url, {method: "POST") fetch(url, {method: "PUT") fetch(url, {method: "DELETE") ===== Általános használat ===== let url = "https://jsonplaceholder.typicode.com/users" fetch(url) .then(response => { if(!response.ok) { throw new Error("Hiba! A REST API elérése sikertelen!") } return response.json() }) .then(result => console.log(result)) .catch(error => console.error(error))