如何摆脱 Node.js 中的 [Object: null prototype]?

Kar*_*ina 14 node.js express

有没有办法摆脱[Object: null prototype]终端中的 ,所以它只会显示{title: 'book'}

console.log(req.body);在 node/express.js 中做

终端

Var*_*lla 23

当我们 console.log 一些具有null原型的对象时,这个额外的[Object: null prototype]问题发生在 Node 中......

这只是意味着该对象不会有它的内置方法......比如 => .toString() 或 .hasOwnProperty() 等......

const obj1 = Object.create(null);
obj1['key'] = 'SomeValue' ;
console.log(obj1); 
>> [Object: null prototype] { 'key' : 'SomeValue' }

const obj2 = {};
obj2['key'] = 'SomeValue' ;
console.log(obj2); 
>> { 'key' : 'SomeValue' } 
Run Code Online (Sandbox Code Playgroud)

当我们将扩展在app.use(urlencoded{ ... })选项设置为true => URL 编码数据由qs库解析时,

当我们将它设置为 false 时,它​​会被查询字符串库解析...

在查询字符串库中(https://nodejs.org/api/querystring.html#querystring_querystring_parse_str_sep_eq_options

它明确指出

querystring.parse()方法返回的对象通常不是从 JavaScript 对象继承的原型。这意味着 obj.toString()、obj.hasOwnProperty() 等典型的Object 方法未定义且无法工作。

或者换句话说,他们有空原型......

这就是为什么在 {extended:false} 的情况下,当我们 console.log(req.body) => 输出在开始时包含额外的[Object: null prototype] ...

对于其他差异,请使用

qs 和 querystring 有什么区别


San*_*ido 5

这听起来像是{extended: false}在解析正文时在 .urlencoded() 中使用。尝试将其删除或更改为 true。

返回几个步骤并编辑它可能看起来像这样

app.use(bodyParser.urlencoded({extended: true}));

或者只是简单地

app.use(bodyParser.urlencoded());

要了解有关扩展选项的更多信息,请阅读文档或此处有人回答得很好 - express 4.0 中的“扩展”是什么意思?


and*_*a-f 1

你可以使用这样的东西:

Reflect.ownKeys(obj).forEach(key => {
  console.log(key + ":" + obj[key]);
});
Run Code Online (Sandbox Code Playgroud)