Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created June 3, 2019 16:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/f0015e3a921f3c77182abda1b2ac2fc0 to your computer and use it in GitHub Desktop.
Save parzibyte/f0015e3a921f3c77182abda1b2ac2fc0 to your computer and use it in GitHub Desktop.
const $btnPeticion = document.querySelector("#btnPeticion"),
$resultados = document.querySelector("#resultados"),
$inputNombre = document.querySelector("#inputNombre");
$btnPeticion.addEventListener("click", () => {
const nombre = $inputNombre.value;
if (!nombre) return alert("Escribe tu nombre");
// Nota: en algunas ocasiones no es posible (por parte del servidor)
// recibir datos en una petición DELETE
const objeto = {
nombre: nombre,
otroDato: "Otro valor :)",
};
$resultados.textContent = "Cargando...";
fetch("https://httpbin.org/delete", {
method: "DELETE", // Indicar método DELETE
body: JSON.stringify(objeto),// Con cuerpo
})
.then(resultadoRaw => {
// Lo decodificamos como json
return resultadoRaw.json();
})
.then(resultadoComoJson => {
// Aquí podemos acceder al objeto JSON, httpbin
// funciona como espejo y devuelve lo que se envía en
// la clave data
// Nota: se hace de nuevo JSON.parse porque devuelve
// el JSON codificado
const datosRecibidosPorServidor = JSON.parse(resultadoComoJson.data);
$resultados.textContent = "Nombre proporcionado: " + datosRecibidosPorServidor.nombre;
$resultados.textContent += "Otro dato proporcionado: " + datosRecibidosPorServidor.otroDato;
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment