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] "
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.
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.
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.
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))
Try this
JSON.stringify(req.body);
Object.prototype.toString will allways return a string with object + type, unless you override it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With