Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert req.body to string?

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] "
like image 271
mobutt Avatar asked Aug 29 '16 17:08

mobutt


People also ask

IS REQ body a string?

A new body string containing the parsed data is populated on the request object after the middleware (i.e. req. body ). This will be a string of the body.

What is req body in Express?

The req. body object allows you to access data in a string or JSON object from the client side. You generally use the req. body object to receive data through POST and PUT requests in the Express server.

What is body in Nodejs?

Body-parser is the Node. js body parsing middleware. It is responsible for parsing the incoming request bodies in a middleware before you handle it. Installation of body-parser module: You can visit the link to Install body-parser module.


2 Answers

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))
like image 87
vkstack Avatar answered Sep 22 '22 12:09

vkstack


Try this

JSON.stringify(req.body);

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

like image 37
delpo Avatar answered Sep 22 '22 12:09

delpo