Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

184
Visualizações
Receiving a node.js response in browser code after a POST of FormData

New to JavaScript. I'm POSTing FormData to a node and attempting to capture a response. The POST works fine but I can't seem to capture the response from the node in the browser code. The contents of res.end(), instead, appear in a new browser page. The code in the xhr.onload function does not get executed.

Either there's something I don't understand or there's something I'm doing wrong (or both).

Any help is appreciated.

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>

node.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);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I resolved this issue by adding headers in the node code.

Changed:

    res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });

to:

    res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8",
                        "Access-Control-Allow-Origin": "*",
                        "Access-Control-Allow-Credentials": "true" });
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda