-
-
Save parzibyte/35b059b42a87c230d289505b2c8557c2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/post", { | |
method: "POST", // Indicar método POST | |
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