本文介绍了如何修复[对象:null原型] {标题:'产品'}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我发布这样的表单时,我已经开始使用express框架学习node.js:

I've started learning node.js with express framework , when I post a form like this :

router.get('/add-product',(req,res,next)=>{
    res.send('<form action="/product" method="POST" ><input type="text" name="title" /><button type="submit">Submit</button></form>');
});

router.post('/product',(req,res,next)=>{
    console.log(req.body);
    res.redirect('/');
});

当我执行console.log(req.body)时,它会显示:

When I do console.log(req.body) it displays:

[Object: null prototype] { title: 'product' }

而不只是{ title: 'product' }

我想知道这实际上是express的错误还是只是最近添加的express的专有性,原因是我下载了去年创建的另一个项目,并且使用相同的方法,当我console.log(req.body)时,它显示了相同的输出.

I'm wondering if this actually is an error with express or just a propriety that its been added to express recently , cause i downloaded another project created last year and it used the same approach, when i console.log(req.body) it display the same output.

预先感谢您的帮助.

推荐答案

那实际上是好的设计.默认情况下,对象继承Object.prototype,其中包含一些助手(.toString().valueOf()).现在,如果您使用req.body且未将任何参数传递给HTTP请求,则您希望req.body为空.如果只是常规对象",就不会:

Thats actually good design. Objects by default inherit the Object.prototype that contains some helpers (.toString(), .valueOf()). Now if you use req.body and you pass no parameters to the HTTP request, then you'd expect req.body to be empty. If it would just be "a regular object" it wouldn't be:

 req.body.toString();

有一种方法可以创建空对象",即没有任何属性/原型的对象,即Object.create(null).您会在控制台中看到这些对象之一.

There is a way to create "empty objects", meaning objects without any properties / prototype, and that is Object.create(null). You are seeing one of those objects in the console.

所以不,这不是一个需要修复的错误,那只是对JS功能的充分利用.

So no, this is not a bug that needs to be fixed, thats just great use of JS' features.

这篇关于如何修复[对象:null原型] {标题:'产品'}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 14:14