How to convert req.body to string?

六月ゝ 毕业季﹏ 提交于 2020-01-01 08:51:49

问题


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] "

回答1:


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))



回答2:


Try this

JSON.stringify(req.body);

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




回答3:


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

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


来源:https://stackoverflow.com/questions/39211596/how-to-convert-req-body-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!