Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

angular - how to fix [Object: null prototype] { title: 'product' }

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('/');
});

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

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

instead of just { title: 'product' }

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That’s actually good design. Objects by default inherit the Object.prototype that contains some helper functions (.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 were just "a regular object", it wouldn't be entirely empty:

console.info(({ "toString": 5 })['toString']);   // 5
console.info(({})['toString']);                  // [Function: toString]

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...