15

I'm attempting to save req.body to a string in node however whenever I do console.log(req.body.toString) the output is [object Object]. Any idea on what i could be doing wrong?

var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

app.post('/addUser', function (req, res) {
    console.log(req.body.toString());
    res.end("thanks\n");
})

Output is:

[object Object]

When using JSON.stringify the output is:

" [object Object] "
mobutt
  • 163
  • 1
  • 1
  • 6

3 Answers3

32

Use JSON.stringify() to convert any JSON or js Object(non-circular) to string. So in your case the following will work.

console.log(JSON.stringify(req.body))
vkstack
  • 1,582
  • 11
  • 24
  • This is also handy because if you've missed and forgot to specify a property you'll know right away what one to use. – tadman Aug 29 '16 at 17:15
2

Try this

JSON.stringify(req.body);

Object.prototype.toString will allways return a string with object + type, unless you override it.

delpo
  • 210
  • 2
  • 18
-1

It is a circular object so u need to stringify it as follow:

console.log(JSON.stringify(req.body));
Mike
  • 14,010
  • 29
  • 101
  • 161