Nuevo en JavaScript. Estoy enviando FormData a un nodo e intentando capturar una respuesta. El POST funciona bien, pero parece que no puedo capturar la respuesta del nodo en el código del navegador. El contenido de res.end(), en cambio, aparece en una nueva página del navegador. El código en la función xhr.onload no se ejecuta.
O hay algo que no entiendo o hay algo que estoy haciendo mal (o ambas cosas).
Cualquier ayuda es apreciada.
html...
<form id="InstallDB" action="http://127.0.0.1:3000" method="POST"> [blah] <input type="submit" value=" Install DB "> </form> <script> var formData = new FormData(document.getElementById("InstallDB")); var xhr = new XMLHttpRequest(); xhr.open("POST", "http://127.0.0.1:3000"); xhr.setRequestHeader("Content-Type", "text/text"); xhr.send(formData); xhr.onload = function(){ if (xhr.status == 200) { console.log("GOT HERE"); console.log(xhr.responseText); } else { alert(`Error ${xhr.status}: ${xhr.statusText}`); } }; xhr.onerror = function() { console.log("Network error occurred") } </script>nodo.js...
const http = require('http'); const hostname = '127.0.0.1'; const port = 3000; const server = http.createServer(function(req, res) { if (req.method === "POST") { var body = ""; req.on("data", function (chunk) { body += chunk; }); req.on("end", function(){ console.log("Server received = " + body); res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" }); res.end(hostname + ", port " + port + ". Successful POST."); }); } }).listen(port, hostname);Resolví este problema agregando encabezados en el código del nodo.
Cambió:
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });a:
res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Credentials": "true" });