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

265
Visualizações
How can a JS Client pass POST parameters to a JS Server?

I'd like to have a pair of Javascript client and server that communicate using JSON without involving a Web Browser. I can get it going as long as the client does not try to send anything to the server. When it does, I get the error message (% node poster.js):

.../node_modules/xhr2/lib/xhr2.js:281
            throw new NetworkError(`Unsupported protocol ${this._url.protocol}`);

Can somebody help me with this protocol issue please. What I have so far: a server that I can start with "pm2 start jsonServer.js" -

var port = 62022
var http = require('http')
var srvr = http.createServer (function (req, res) {
        console.log ('Request type: ' + typeof(req))
        console.log (req)
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.write('Hello World!\n');
        res.write(req);
        res.end();
})
var scriptName = __filename.split(__dirname+"/").pop();
console.log ('Script: ' + scriptName +'. Listening to port ' + port)
srvr.listen(port)

... and a client that is

var XMLHttpRequest = require('xhr2')

var serialize = function(object) {
  return JSON.stringify(object, null, 2)
}

let xhr = new XMLHttpRequest();
xhr.open("POST", "localhost:62022");

xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");

xhr.onload = () => console.log(xhr.responseText);

let data = `{
  "Id": 912,
  "First Name": "Archibald",
  "Last Name": "Haddock"
}`;
//console.log (serialize(data));
//xhr.send(serialize(data));
console.log (data);
xhr.send(data);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

This is what is needed after posting 'Hello World!' on the server (res.end does not wait for the async data transfer):

        let data = '';
        req.on('data', chunk => {
                data += chunk;
        });
        req.on('end', () => {
                // do whatever with data
                res.write ('Data: ' + data + '\n')
                res.end()
        });
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