Javascript 如何将 req.body 转换为字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39211596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:20:16  来源:igfitidea点击:

How to convert req.body to string?

javascriptnode.jsexpress

提问by mobutt

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?

我试图将 req.body 保存到节点中的字符串,但是每当我执行 console.log(req.body.toString) 时,输出都是 [object Object]。知道我可能做错了什么吗?

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]

[object Object]

When using JSON.stringify the output is:

使用 JSON.stringify 时,输出为:

" [object Object] "

回答by vkstack

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

使用JSON.stringify()任何JSON或JS对象(非圆)转换为字符串。因此,在您的情况下,以下内容将起作用。

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

回答by delpo

Try this

尝试这个

JSON.stringify(req.body);

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

Object.prototype.toString 将始终返回带有对象 + 类型的字符串,除非您覆盖它。

回答by Muhamad Eissa

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

它是一个圆形对象,因此您需要将其字符串化如下

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