Home > Software design >  bodyParser returns object and not String
bodyParser returns object and not String

Time:10-29

I'm trying to implement a json content listener using express and body-parser in Typescript and so far everything works perfectly except when I receive the json webhook the console logs it as an object and NOT a string

import express from 'express';
import bodyParser from 'body-parser';


// Initialize express and define a port
const app = express();
const PORT = 3000;

// Start express on the defined port
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));


//Some rudimentary error handling
app.use((err, req, res, next) => {
  console.log(err.stack);
  console.log(err.name);
  console.log(err.code);
  res.status(500).json({ message: 'Shit hit the fan hard' 
  });
})
// Parse JSON
app.use(bodyParser.json());

//Create route (url that will be set as webhook url)
app.post('/webhook', (req, res, next) => {
console.log("Headers: "   req.headers.toString());
console.log("Body: "   req.body.toString());
 next()
res.status(200).end();
});

It returns the following in the console

Server running on port 3000
Headers: [object Object]
Body: [object Object]

Now for example if I try to log the data as follows the "status" key's value is properly parsed and logged

console.log("Status: "   req.body.status);

Any ideas why that might be happening?

CodePudding user response:

Use JSON.stringify() to convert any JSON or js Object(non-circular) to string.

console.log(JSON.stringify(req.body))

So in your case it would be the following:

//Create route (url that will be set as webhook url)
app.post('/webhook', (req, res, next) => {
console.log("Headers: "   JSON.stringify(req.headers));
console.log("Body: "   JSON.stringify(req.body));
 next()
res.status(200).end();
});
  • Related