Home > Back-end >  How to access body of request made with nodejs http library
How to access body of request made with nodejs http library

Time:03-22

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.post('/', (req, res) => {
    console.log(req.body); // undefined
    res.send();
});

app.use(express.json());

app.listen(8080);

I have to use the http library of nodejs.

CodePudding user response:

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.

CodePudding user response:

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.

  • Related