How to print the response body (or the request body when POST) in Node.js using Express?

14,087

In your code you are doing

router.get('/companies', function(req, res){
  console.log(res.body);
});

While it should be

router.get('/companies', function(req, res){
  console.log(req.body); // req, not res altough it shouldn't be set for GET
});

You wanted to print Request body not Response (which is unset, of course). Let me know if it solved your issue.

[edit]

Since you ask to me how would I do it, probably you should note that using console.log is not how I'd log something in production. Rather I'd use a logging library like bunyan, which is extensible and features a json-only logging. I like their vision that logs should be though for machines and not for humans, by the way they also provide a binary tool to pretty print JSON in a more human friendly format. It's extensible and you can find a lot of plugins (referred to as "streams") that log also to log aggregators and third party services should you need that kind of feature.

Uh, and of course there are a lot of other valid alternatives out there.

[update as per OP comment]

I think I now understand what you're trying to achieve. You should have a look at the response actually after it has been generated. Where you are trying to print something you didn't even touch the response object, so it should not be modified (unless you have some middleware doing that for you -e.g. putting some header-). Refer to a library such as on-finished and you'll get the response object right before to send it to the client.

You don't explicitly state your express or node version so I can only guess, but give it a try.

You could also go with plain node.js APIs.

Also you might just put another middleware right after your handler and pass the request next to it with a response set and just log (express router is stack-based so unless you terminate the request you are able to pass in several handlers).

BTW I'd just try our the Node.js API or the library I posted to you.

Let me know if I've understood what you meant to do.

Share:
14,087
Uddipta_Deuri
Author by

Uddipta_Deuri

Updated on June 04, 2022

Comments

  • Uddipta_Deuri
    Uddipta_Deuri almost 2 years
    var express = require('express');
    var bodyParser = require('body-parser');
    var mongoose = require('mongoose');
    mongoose.Promise = require('bluebird');
    
    
    mongoose.connect("mongodb://localhost/placement-process");
    
    var app = express();
    
    app.use(bodyParser.urlencoded({extended:true}));
    app.use(bodyParser.json());
    
    var router = require('./router');
    app.use('/api', router);
    
    router.get('/companies', function(req, res){
        console.log(res.body);
    });
    
    
    app.listen(3000);
    

    I am making GET requests to /api/companies using POSTMAN for Chrome browser. But I am not getting any output in my console. What am I doing wrong? Or how would you do it?