fetchExplicación breve, pasos y ejemplos interactivos para aprender a usar fetch en el navegador.
fetch?fetch(url, options). Opcional: method, headers, body.Response.response.ok o response.status para detectar errores HTTP.response.json(), response.text() o response.blob() (estas también devuelven Promises).try/catch o .catch(). Nota: fetch RECHAZA la Promise solo por fallos de red; respuestas 4xx/5xx no rechazan por sí mismas.// Código usado en el ejemplo:
async function simpleGet(){
const res = await fetch('https://randomuser.me/api/');
if (!res.ok) throw new Error(res.status);
const data = await res.json();
return data.results[0];
}
// Código usado en el ejemplo:
async function postJson(){
const res = await fetch('https://jsonplaceholder.typicode.com/posts',{
method:'POST',
headers:{'Content-Type':'application/json'},
body: JSON.stringify({title:'Hola',body:'Contenido',userId:1})
});
return await res.json();
}
response.ok// Código usado:
async function withErrors(){
try{
const res = await fetch('https://httpstat.us/500');
if(!res.ok) throw new Error('HTTP ' + res.status);
return await res.text();
}catch(e){
throw e;
}
}
response.ok antes de procesar el cuerpo.Content-Type: application/json cuando mandes JSON.try/catch con async/await o .catch() para errores de red.