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

136
Visualizações
How to access body of request made with nodejs http library

I'm trying to make a post request passing json data. When the request arrives on my express server, it does not have a body. What am I doing wrong?

const http = require('http');
const req = http.request({
         hostname: 'localhost',
         port: 8080,
         path: '/',
         method: 'POST'
        }, (res) => {

    res.on('end', () => {
        // 
    });
});

req.write(JSON.stringify({ something: 'something' }));

req.end();

const express = require('express');
const app = express();
app.use(express.json());

app.post('/', (req, res) => {
    console.log(req.body); // undefined
    res.send();
});

app.listen(8080);

I have to use the http library of nodejs.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You should:

  • Move the line where you register the JSON parsing middleware so it appears before the line where you register the / handler. Handlers are called in order so with your current approach, the / will fire and end the chain without reaching the middleware.
  • Add a Content-Type: application/json request header to the client-side code so that the body parser will not skip over it because it doesn't recognise the (un)declared data type.
about 4 years ago · Juan Pablo Isaza Relatório

0

8bitIcon could be right. This behavior could be the result of not using a middle ware that parses the body of your request. Check out this post, might help you to solve the problem.

Thank you.

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