{"id":1569,"date":"2024-08-02T07:25:14","date_gmt":"2024-08-02T05:25:14","guid":{"rendered":"https:\/\/blog.sutilweb.eu\/?page_id=1569"},"modified":"2024-08-02T07:25:15","modified_gmt":"2024-08-02T05:25:15","slug":"003-ajax-api-fetch","status":"publish","type":"page","link":"https:\/\/sutilweb.eu\/index.php\/lenguajes\/javascript\/javascript-practico\/15-ajax\/003-ajax-api-fetch\/","title":{"rendered":"003. AJAX: API Fetch"},"content":{"rendered":"\n<p>El <strong>API de Fetch<\/strong>, la documentaci\u00f3n de <a href=\"https:\/\/developer.mozilla.org\/es\/docs\/Web\/API\/fetch\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>MDN<\/strong> <\/a>lo menciona como un mecanismo m\u00e1s \u00f3ptimo para hacer peticiones <strong>XMLHttpRequest<\/strong>, lo que significa que tras bambalinas, <strong>Fetch<\/strong> trabaja con <strong>XMLHttpRequest<\/strong>. A d\u00eda de hoy, <strong>Fetch<\/strong> es compatible con todos los navegadores, salvo <strong>Internet Explorer<\/strong>.<\/p>\n\n\n\n<!--more-->\n\n\n\n<p><strong>Fetch<\/strong> es mucho m\u00e1s r\u00e1pido que <strong>XMLHttpRequest<\/strong> a la hora de consumir <strong>APIs<\/strong>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Funcionamiento de Fetch<\/h2>\n\n\n\n<p>Para ello utilizamos el m\u00e9todo <strong><em>fetch()<\/em><\/strong> haciendo referencia al recurso. Adicionalmente podemos pasar un objeto con opciones, que las veremos cuando hagamos un <strong>CRUD<\/strong> con <strong>Fetch<\/strong>.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p><strong>Nota<\/strong>: el m\u00e9todo por defecto para Fetch es GET<\/p>\n<\/blockquote>\n\n\n\n<p><strong>Fetch<\/strong> es un mecanismo que trabaja con promesas, con lo que la resultante de <strong>fetch<\/strong> nos devolver\u00e1 un m\u00e9todo <strong><em>then()<\/em><\/strong> para la siguiente iteraci\u00f3n de c\u00f3digo, y para capturar nuestro c\u00f3digo de error utilizaremos el m\u00e9todo <strong><em>catch()<\/em><\/strong>, y si necesitamos ejecutar un c\u00f3digo s\u00ed o s\u00ed, utilizaremos el m\u00e9todo <strong><em>finally()<\/em><\/strong>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Archivos<\/h2>\n\n\n\n<p>Vamos a tener dos archivos, <em>fetch.html<\/em> y <em>fetch.js<\/em>, que tienen la siguiente sintaxis.<\/p>\n\n\n\n<p>La sintaxis de <em>fetch.html<\/em> es.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;!DOCTYPE html&gt;\n&lt;html lang=\"en\"&gt;\n&nbsp; &lt;head&gt;\n&nbsp; &nbsp; &lt;meta charset=\"UTF-8\" \/&gt;\n&nbsp; &nbsp; &lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" \/&gt;\n&nbsp; &nbsp; &lt;title&gt;Fetch Ajax&lt;\/title&gt;\n&nbsp; &lt;\/head&gt;\n&nbsp; &lt;body&gt;\n&nbsp; &nbsp; &lt;h1&gt;Ajax&lt;\/h1&gt;\n&nbsp; &nbsp; &lt;h2&gt;Fetch Ajax&lt;\/h2&gt;\n&nbsp; &nbsp; &lt;ol id=\"fetch\"&gt;&lt;\/ol&gt;\n&nbsp; &nbsp; &lt;script src=\".\/02fetch.js\"&gt;&lt;\/script&gt;\n&nbsp; &lt;\/body&gt;\n&lt;\/html&gt;<\/pre>\n\n\n\n<p>La sintaxis de <em>fetch.js<\/em> es<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">(() =&gt; {\n&nbsp; const $fetch = document.getElementById(\"fetch\"),\n&nbsp; &nbsp; $fragment = document.createDocumentFragment();\n&nbsp; fetch(\"https:\/\/jsonplaceholder.typicode.com\/users\")\n&nbsp; &nbsp; .then((res) =&gt; {\n&nbsp; &nbsp; &nbsp; return res.ok ? res.json() : Promise.reject(res);\n&nbsp; &nbsp; })\n&nbsp; &nbsp; .then((json) =&gt; {\n&nbsp; &nbsp; &nbsp; json.forEach((el) =&gt; {\n&nbsp; &nbsp; &nbsp; &nbsp; const $li = document.createElement(\"li\");\n&nbsp; &nbsp; &nbsp; &nbsp; $li.innerHTML = `${el.name} --- ${el.email} --- ${el.phone}`;\n&nbsp; &nbsp; &nbsp; &nbsp; $fragment.appendChild($li);\n&nbsp; &nbsp; &nbsp; });\n&nbsp; &nbsp; &nbsp; $fetch.appendChild($fragment);\n&nbsp; &nbsp; })\n&nbsp; &nbsp; .catch((err) =&gt; {\n&nbsp; &nbsp; &nbsp; let message = err.statusText || \"Ocurri\u00f3 un error\";\n&nbsp; &nbsp; &nbsp; $fetch.innerHTML = `Error: ${err.status}: ${message}`;\n&nbsp; &nbsp; })\n&nbsp; &nbsp; .finally(() =&gt; {\n&nbsp; &nbsp; &nbsp; console.log(\n&nbsp; &nbsp; &nbsp; &nbsp; \"Esto se ejecutar\u00e1 independientemente del resultado de la promesa Fetch\"\n&nbsp; &nbsp; &nbsp; );\n&nbsp; &nbsp; });\n})();<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>El API de Fetch, la documentaci\u00f3n de MDN lo menciona como un mecanismo m\u00e1s \u00f3ptimo para hacer peticiones XMLHttpRequest, lo [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":1561,"menu_order":2,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_uag_custom_page_level_css":"","site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"class_list":["post-1569","page","type-page","status-publish","hentry"],"uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false},"uagb_author_info":{"display_name":"Sutil Web","author_link":"https:\/\/sutilweb.eu\/index.php\/author\/sutilweb\/"},"uagb_comment_info":0,"uagb_excerpt":"El API de Fetch, la documentaci\u00f3n de MDN lo menciona como un mecanismo m\u00e1s \u00f3ptimo para hacer peticiones XMLHttpRequest, lo [&hellip;]","_links":{"self":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1569","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/comments?post=1569"}],"version-history":[{"count":1,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1569\/revisions"}],"predecessor-version":[{"id":1570,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1569\/revisions\/1570"}],"up":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1561"}],"wp:attachment":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/media?parent=1569"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}