Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!