Guía de la API Fetch de JavaScript: GET, POST, manejo de errores y ejemplos del mundo real

1. Introducción

JavaScript es uno de los lenguajes de programación más utilizados en el desarrollo web. Entre sus muchas características, la Fetch API ha cobrado relevancia como una capacidad importante para habilitar la comunicación asíncrona.

En este artículo explicamos la Fetch API en detalle, desde los conceptos básicos hasta usos más avanzados. Al comprenderla, podrás implementar la obtención de datos y la comunicación con el servidor de forma más fluida en aplicaciones web.

¿Qué es la comunicación asíncrona?

La comunicación asíncrona es un método de intercambio de datos con un servidor mientras se continúa con otros procesos sin bloquearse hasta que la comunicación finalice. Esto mejora la capacidad de respuesta de la interfaz de usuario y facilita el manejo de datos sin frustraciones.

Por ejemplo, cuando un usuario hace clic en un botón de una página web para obtener datos, otras tareas pueden continuar sin esperar la respuesta del servidor, mejorando considerablemente la experiencia del usuario.

¿Qué es la Fetch API?

La Fetch API es una interfaz moderna para realizar comunicación asíncrona en JavaScript. Fue introducida como alternativa al tradicional XMLHttpRequest (XHR), ofreciendo una sintaxis concisa y una configuración flexible.

Con esta API, puedes escribir fácilmente la lógica para recuperar datos de un servidor o enviar datos a un servidor.

En las secciones siguientes, presentaremos todo paso a paso, desde el uso básico de la Fetch API hasta ejemplos prácticos del mundo real.

2. ¿Qué es la Fetch API?

La Fetch API es la interfaz estándar más reciente para realizar comunicación asíncrona en JavaScript. En esta sección explicamos su función básica y cómo se diferencia de los enfoques tradicionales.

Visión general de la Fetch API

La Fetch API está diseñada para obtener recursos a través de una red.
Esto facilita que las aplicaciones web se comuniquen con servidores.

Características clave

  • Basada en Promesas: No es necesario depender de funciones de devolución de llamada, lo que permite escribir código más legible.
  • Sintaxis concisa: En comparación con XMLHttpRequest, puede reducir significativamente la cantidad de código.
  • Alta flexibilidad: Puedes personalizar solicitudes y respuestas en detalle.
  • Diseño moderno: Funciona bien con las características modernas de JavaScript, lo que permite un código mantenible.

A continuación se muestra un ejemplo básico de uso de la Fetch API.

fetch('https://api.example.com/data')
  .then(response => response.json()) // Convert to JSON
  .then(data => console.log(data))  // Output the data
  .catch(error => console.error('Error:', error)); // Error handling

Este código obtiene datos de la URL especificada, los convierte a JSON y los muestra en la consola. Si ocurre un error, imprime un mensaje de error.

Diferencias con el tradicional XMLHttpRequest

La Fetch API es un enfoque nuevo que reemplaza al ampliamente usado XMLHttpRequest (XHR). La tabla siguiente compara ambos.

FeatureFetch APIXMLHttpRequest
Code simplicityConcise, readable syntaxOften complex with many callbacks
Asynchronous handlingSupports Promises and offers high flexibilityRequires callback functions
Stream processingNative supportRequires additional handling
Working with JSONEasy to handleRequires explicit parsing
Error handlingFlexible and can be centralizedOften becomes complex

Como puedes observar, la Fetch API resulta atractiva por su diseño conciso y moderno. En particular, al estar basada en Promesas permite escribir lógica asíncrona de forma más natural.

Resumen

La Fetch API es una herramienta poderosa y fácil de usar para la comunicación asíncrona en JavaScript. Al ser más simple de implementar que el XHR tradicional, se ha convertido en una habilidad esencial para el desarrollo web moderno.

En la siguiente sección, revisaremos patrones de uso concretos de la Fetch API con ejemplos de código.

3. Uso básico de la Fetch API

En esta sección explicamos el uso básico de la Fetch API con ejemplos de código concretos. Cubrimos principalmente los siguientes puntos.

  • Sintaxis del método fetch() y un ejemplo básico
  • Cómo implementar una solicitud GET
  • Cómo manejar los datos de la respuesta

Sintaxis básica del método fetch()

Con la Fetch API, envías solicitudes a un servidor mediante el método fetch(). A continuación se muestra la sintaxis básica.

fetch(url, options)
  .then(response => {
    // Handle the response
  })
  .catch(error => {
    // Handle errors
  });

Argumentos

  • url : La URL a la que se envía la solicitud.
  • options (opcional): Configuraciones de opciones que incluyen método, encabezados, cuerpo y más.

Valor de retorno

  • Objeto Promise : Devuelve el resultado del proceso asíncrono.

Cómo implementar una solicitud GET

El uso más básico de la API Fetch es una solicitud GET, que recupera datos de un servidor.

Ejemplo: Recuperar datos JSON

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network error');
    }
    return response.json(); // Retrieve data as JSON
  })
  .then(data => {
    console.log(data); // Display the retrieved data
  })
  .catch(error => {
    console.error('Error:', error); // Print an error log
  });

Cómo procesar los datos de respuesta

Con la API Fetch, puedes procesar los datos de respuesta en varios formatos. A continuación, se muestran ejemplos comunes.

  1. Recuperar datos de texto
    fetch('https://example.com/data.txt')
      .then(response => response.text()) // Retrieve data as text
      .then(data => console.log(data))
      .catch(error => console.error('Error:', error));
    
  1. Recuperar datos binarios
    fetch('https://example.com/image.jpg')
      .then(response => response.blob()) // Retrieve as binary data
      .then(blob => {
        const imgURL = URL.createObjectURL(blob);
        document.querySelector('img').src = imgURL;
      })
      .catch(error => console.error('Error:', error));
    
  1. Recuperar información de encabezados
    fetch('https://example.com/api')
      .then(response => {
        console.log(response.headers.get('Content-Type')); // Get a header value
      })
      .catch(error => console.error('Error:', error));
    

Resumen

Aquí, cubrimos una solicitud GET básica usando la API Fetch y cómo manejar las respuestas.

La API Fetch es una herramienta flexible que facilita la recuperación de muchos tipos de datos, como texto, JSON y datos binarios. Una vez que entiendas estos fundamentos, será más fácil aplicarlos al siguiente capítulo, incluyendo el manejo de errores y solicitudes POST.

En la siguiente sección, explicaremos el manejo de errores con la API Fetch en detalle.

4. Manejo de errores

En esta sección, explicamos el manejo de errores al usar la API Fetch. Al comunicarse con un servidor, pueden ocurrir varios problemas, como errores de red y errores de respuesta. Manejar estos adecuadamente puede mejorar la experiencia del usuario.

Fundamentos del manejo de errores

Con la API Fetch, puedes usar el método catch() para manejar casos como fallos de red o respuestas de error.

Ejemplo básico de manejo de errores

fetch('https://example.com/data')
  .then(response => {
    if (!response.ok) { // Check the response status code
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('An error occurred:', error)); // Error handling

Manejo de errores con try…catch

Usar Async/Await te permite escribir código más limpio y legible. En ese caso, manejas los errores con una declaración try...catch.

Ejemplo: Manejo de errores con Async/Await

async function fetchData() {
  try {
    const response = await fetch('https://example.com/data');
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('An error occurred:', error);
  }
}

fetchData();

Implementación de tiempos de espera

La API Fetch no incluye una función de tiempo de espera integrada por defecto. Sin embargo, implementar tiempos de espera te permite manejar respuestas lentas de manera adecuada.

Ejemplo: Implementación de un tiempo de espera

function fetchWithTimeout(url, timeout = 5000) {
  return Promise.race([
    fetch(url),
    new Promise((_, reject) =>
      setTimeout(() => reject(new Error('Request timed out')), timeout)
    ),
  ]);
}

fetchWithTimeout('https://example.com/data', 5000)
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('An error occurred:', error));

Detecting network errors

A network error refers to cases where the server cannot be reached or the connection is interrupted. With the Fetch API, these errors can also be detected with catch().

Example: Handling a network error

fetch('https://invalid-url.com/data')
  .then(response => response.json())
  .catch(error => console.error('Network error:', error.message));

Summary

In this section, we introduced error handling with the Fetch API, from basics to more advanced patterns.

Key takeaways

  • Check response status codes and implement error handling
  • Simplify error handling with Async/Await
  • Handle slow responses by implementing timeouts

Error handling is critical for improving the user experience. In the next section, we’ll explain POST requests for sending data to a server.

5. Sending POST requests

In this section, we explain how to send POST requests with the Fetch API to send data to a server. We’ll cover practical examples such as sending form data and JSON.

Basic syntax for POST requests

You can implement a POST request in the Fetch API by providing an options object as the second argument to the fetch() method.

Basic syntax

fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Example: Sending JSON data

Below is an example of sending user information in JSON format.

const userData = {
  name: 'Taro Yamada',
  email: 'yamada@example.com',
};

fetch('https://example.com/api/users', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(userData),
})
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log('Success:', data))
  .catch(error => console.error('Error:', error));

Example: Sending form data

To send form data, use the FormData object.

const formData = new FormData();
formData.append('username', 'yamada');
formData.append('file', fileInput.files[0]);

fetch('https://example.com/upload', {
  method: 'POST',
  body: formData,
})
  .then(response => response.json())
  .then(data => console.log('Upload success:', data))
  .catch(error => console.error('Error:', error));

Example: Requests with authentication information

When sending data along with authentication information (for example, a token), add the auth data to the request headers.

fetch('https://example.com/api/protected', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
  },
  body: JSON.stringify({ message: 'Hello!' }),
})
  .then(response => response.json())
  .then(data => console.log('Success:', data))
  .catch(error => console.error('Error:', error));

Error handling for POST requests

For POST requests, you can add error handling like the following to deal with network issues or server-side problems.

async function postData(url, data) {
  try {
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    const result = await response.json();
    console.log('Success:', result);
  } catch (error) {
    console.error('An error occurred:', error.message);
  }
}

postData('https://example.com/api/messages', { text: 'Hello!' });

Summary

In this section, we explained the basics and practical usage of POST requests using the Fetch API.

Key takeaways

  1. How to send JSON data and form data
  2. How to implement requests with authentication information
  3. How to strengthen error handling

POST requests are essential for two-way communication with servers. In the next section, we’ll explain customization options for the Fetch API in detail.

6. Other option settings

In this section, we explain various option settings you can specify as the second argument to the Fetch API. By using these, you can easily customize requests and manage authentication information.

Basic option syntax

Fetch API options are specified as an object in the second argument.

fetch(url, {
  method: 'GET',              
  headers: {                  
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
  },
  body: JSON.stringify(data), 
  credentials: 'include',     
  mode: 'cors',               
  cache: 'no-cache',          
  redirect: 'follow',         
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

Details of each option

  1. method (HTTP method)
  • Specifies the HTTP method (for example: GET, POST, PUT, DELETE).
  • The default is GET .
  1. headers (headers)
  • Specifies request headers.
  • Used to define the data format or add authentication information.
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
    }
    
  1. body (sending data)
  • Used to send data to the server with POST or PUT methods.
  1. credentials (managing credentials)
  • Controls whether credentials (cookies or HTTP authentication data) are sent.
ValueDescription
omitDo not send credentials (default)
same-originSend credentials only for same-origin requests
includeSend credentials even for cross-origin requests
  1. mode (CORS policy)
  • Controls cross-origin request behavior.
ValueDescription
corsAllow cross-origin requests (default)
no-corsAllow only simple requests (limited)
same-originAllow requests only to the same origin
  1. cache (cache control)
  • Controls how request caching is used.
ValueDescription
defaultUse the browser’s default cache settings
no-storeDo not use cache; always make a new request
reloadIgnore cache and make a new request
  1. redirect (redirect handling)
  • Specifies how redirects are handled.
ValueDescription
followAutomatically follow redirects (default)
errorTreat redirects as errors
manualHandle redirects manually (controllable in code)

Advanced customization example

Below is an example that combines multiple options.

fetch('https://example.com/api/resource', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
  },
  body: JSON.stringify({ message: 'Hello!' }),
  credentials: 'include',
  mode: 'cors',
  cache: 'no-cache',
  redirect: 'follow',
})
  .then(response => response.json())
  .then(data => console.log('Success:', data))
  .catch(error => console.error('Error:', error));

Summary

In this section, we explained various Fetch API option settings in detail.

Key takeaways

  1. How to customize headers and credentials
  2. Fine-grained settings such as CORS and cache control
  3. Advanced patterns for redirects and error handling

In the next section, we’ll introduce concrete examples of how to use the Fetch API in practice.

7. Practical examples of using the Fetch API

In this section, we explain how you can use the Fetch API in real projects with concrete examples. Through practical scenarios, you’ll build real-world Fetch API skills.

Displaying a list of API data

A common use case in web applications is fetching data from an external API and displaying it as a list. In the example below, we fetch post data from the JSONPlaceholder API and display it as an HTML list.

Code example

const url = 'https://jsonplaceholder.typicode.com/posts';

fetch(url)
  .then(response => {
    if (!response.ok) {
      throw new Error(`¡Error HTTP! Estado: ${response.status}`);
    }
    return response.json();
  })
  .then(posts => {
    const list = document.getElementById('post-list');
    posts.forEach(post => {
      const listItem = document.createElement('li');
      listItem.textContent = `${post.id}: ${post.title}`;
      list.appendChild(listItem);
    });
  })
  .catch(error => console.error('Error:', error));

HTML example

<ul id="post-list"></ul>

Submitting a form and registering data

This is an example of registering data from a form input to a server.

Code example

const form = document.getElementById('user-form');
form.addEventListener('submit', async (e) => {
  e.preventDefault();

  const formData = {
    name: document.getElementById('name').value,
    email: document.getElementById('email').value,
  };

  try {
    const response = await fetch('https://jsonplaceholder.typicode.com/users', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(formData),
    });

    if (!response.ok) {
      throw new Error(`¡Error HTTP! Estado: ${response.status}`);
    }

    const result = await response.json();
    console.log('Registro exitoso:', result);
    alert('¡El usuario ha sido registrado!');
  } catch (error) {
    console.error('Error:', error);
    alert('Ocurrió un error.');
  }
});

HTML example

<form id="user-form">
  <input type="text" id="name" placeholder="Nombre" required />
  <input type="email" id="email" placeholder="Dirección de correo" required />
  <button type="submit">Registrarse</button>
</form>

File upload

The Fetch API can also handle file uploads. Below is an example of uploading an image file to a server.

Code example

const fileInput = document.getElementById('file-input');
const uploadButton = document.getElementById('upload-button');

uploadButton.addEventListener('click', async () => {
  const file = fileInput.files[0];
  const formData = new FormData();
  formData.append('file', file);

  try {
    const response = await fetch('https://example.com/upload', {
      method: 'POST',
      body: formData,
    });

    if (!response.ok) {
      throw new Error(`¡Error HTTP! Estado: ${response.status}`);
    }

    const result = await response.json();
    console.log('Carga exitosa:', result);
    alert('¡El archivo ha sido subido!');
  } catch (error) {
    console.error('Error:', error);
    alert('La carga falló.');
  }
});

HTML example

<input type="file" id="file-input" />
<button id="upload-button">Subir</button>

Summary

In this section, we introduced practical examples using the Fetch API.

Key takeaways

  1. Creating a dynamic list by displaying API data
  2. Implementing form submission and data registration
  3. Implementing file uploads and search functionality

By using these examples as references, you can build interactive web applications powered by the Fetch API. In the next section, we’ll summarize the entire article and introduce learning resources for your next steps.

8. Summary

In this article, we explained JavaScript’s Fetch API systematically—from the basics to practical use. The Fetch API is a powerful tool that enables asynchronous communication concisely and efficiently, making it essential for modern web application development.

Review of what you learned

  1. Overview and features of the Fetch API
  • The Fetch API is Promise-based, allowing concise and flexible code.
  • Compared to traditional XMLHttpRequest, the syntax is simpler and easier to maintain.
  1. Basic usage and error handling
  • Basic syntax for fetching data with GET requests.
  • By adding error handling and timeout processing, you can implement more robust code.
  1. Sending data with POST requests
  • Ejemplos de envío de datos JSON y datos de formulario.
  • Aprendiste cómo agregar información de autenticación y encabezados personalizados.
  1. Uso eficaz de la configuración de opciones
  • Se introdujeron métodos de personalización flexibles como control de caché, configuraciones CORS y gestión de credenciales.
  1. Ejemplos prácticos
  • Aprendiste el uso real mediante ejemplos como visualización de listas, envío de formularios, carga de archivos y funcionalidad de búsqueda.

Ventajas y aspectos a considerar para la Fetch API

Ventajas

  • El código es conciso y altamente legible.
  • Funciona bien con Promises y Async/Await, facilitando su combinación con la sintaxis moderna de JavaScript.
  • Soporta muchos formatos de datos como JSON, datos binarios y streams.

Aspectos a considerar

  • No incluye una función de tiempo de espera por defecto, por lo que puede ser necesario implementarla manualmente.
  • No es compatible con navegadores antiguos (por ejemplo, Internet Explorer), por lo que se deben considerar polyfills o alternativas si es necesario.

Recursos de aprendizaje para los siguientes pasos

Para profundizar tu comprensión de la Fetch API, utiliza la documentación oficial y los recursos a continuación.

Finalmente

La Fetch API es una herramienta poderosa que permite implementar la comunicación con el servidor de forma sencilla usando técnicas modernas de JavaScript. Al aplicar lo que aprendiste en este artículo, podrás crear aplicaciones web más interactivas y con más funcionalidades.

A medida que el desarrollo web sigue evolucionando, la integración de APIs y el procesamiento asíncrono serán cada vez más importantes. ¡Domina la Fetch API y perfecciona tus habilidades prácticas!

Próximos pasos

  • Intenta crear un proyecto que utilice una API real.
  • Usa opciones personalizadas para implementar un manejo de solicitudes más avanzado.
  • Desafíate a construir aplicaciones full-stack que se integren con un backend del lado del servidor.

Esto concluye el artículo. ¡Esperamos que aprender la Fetch API te ayude a mejorar tus habilidades aún más!

広告