Search code examples
javascriptnode.jsexpresspostmanadvanced-rest-client

req.body isn't appearing as one of key-value pairs, but req.headers and others do


Sample 'Advanced REST Client' Request

I'm using Postman and Advanced REST client to create a basic POST request for the following code -

'use strict';
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var http = require('http');

// configure the app to use bodyParser()
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(bodyParser.json());
//app.listen(6666);

http.createServer(function (req, res) {
    h2s(req, res);
}).listen(6666, '127.0.0.1');

console.log('Server running at http://127.0.0.1:6666/');

module.exports = function h2s(req, res) {
    console.log("inside h2s");
    app.use(function (req, res) {
        console.log("req.body : " + req.body);
        res.send("OK");
    });
}

But, when I debug, I find that req.body is missing in the "req object tree". What's more strange is all the changes that I make to req.headers are available in the req object tree.

Looks like I seem to be making a trivial mistake, but I'm unable to figure it out. Been trouble-shooting for an hour or so but no luck!

Can anyone of you figure out why req.body seems to be missing from the req object tree?

Will be of great help to me. Thanks!


Solution

  • It looks like you have several issues in your code:

    instead of

    http.createServer(function (req, res) {
        h2s(req, res);
     }).listen(6666, '127.0.0.1');
    
    console.log('Server running at http://127.0.0.1:6666/');
    
    module.exports = function h2s(req, res) {
        console.log("inside h2s");
        app.use(function (req, res) {
        console.log("req.body : " + req.body);
        res.send("OK");
       });
    }
    

    For creating the server, try

    http.createServer(app).listen(8000, '127.0.0.1'); //using http
    

    Or (using express directly)

    app.listen(8000,function(){
        console.log('Server running at http://127.0.0.1:8000/');
    });
    

    Then register an handler function for your requests, there you can access req.body

    app.use(function (req, res) {
        console.log("req.body : " + req.body);
        res.send("OK");
    });