Anthony Anthony - 2 months ago 12
Node.js Question

How log an HTTP JSON request in Loopback app deployed on Heroku?

An app (Loopback) is deployed on Heroku, and I need to to see the req body (the JSON) send to this app for debugging purpose.

So the access to the log is :

heroku logs --tail


The server.js is like the following :

var loopback = require('loopback');
var boot = require('loopback-boot');

var app = module.exports = loopback();

app.start = function() {
// start the web server
return app.listen(function() {
app.emit('started');
console.log('Web server listening at: %s', app.get('url'));
});
};

// Bootstrap the application, configure models, datasources and middleware.
// Sub-apps like REST API are mounted via boot scripts.
boot(app, __dirname, function(err) {
if (err) throw err;

// start the server if `$ node server.js`
if (require.main === module)
app.start();
});

Answer

As loopback extends express, we can use body parser module. So first install "body-parser"

Then add this code in serveur.js

var loopback = require('loopback');
var boot = require('loopback-boot');

var app = module.exports = loopback();

var bodyParser = require('body-parser');

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))

// parse application/json
app.use(bodyParser.json())

var logger = function(req, res, next) {
  console.log(JSON.stringify(req.body, null, 2));
  next(); // Passing the request to the next handler in the stack.
}
app.use(logger);

...

The remote log will display every request body received by the server.

Comments