Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created June 3, 2019 16:22
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/33b0f87b3b020fefdab36d23e9da271e to your computer and use it in GitHub Desktop.
Save parzibyte/33b0f87b3b020fefdab36d23e9da271e 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");
const objeto = {
nombre: nombre,
otroDato: "Otro valor :)",
};
$resultados.textContent = "Cargando...";
fetch("https://httpbin.org/put", {
method: "PUT", // Indicar método PUT
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