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

流过昼夜 提交于 2019-12-30 18:48:31

问题


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 , 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.

Thanks in advance for your help.


回答1:


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

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, thats just great use of JS' features.




回答2:


You can try this:

app.use(express.urlencoded({ extended: false }));



回答3:


I get some problem and my terminal showed me below explanation

body-parser deprecated undefined extended: provide extended option at express

and i used this app.use(bodyParser.urlencoded({extended: false}))

or

you are running a version of Express that is 4.16+ then type just

app.use(express.urlencoded({extended: true}))

I think it helps you

To find out more about the extended option, read the docs or someone here has answered it well - What does 'extended' mean in express 4.0?




回答4:


I would recommend you to use an inspect tool such as util to log objects neatly.

i.e:

const util = require('util'); util.inspect(req.body, false, null);




回答5:


I recommmend to use the function JSON.parse like that:

const form = JSON.parse(JSON.stringify(req.body)) console.log(form.title)



来源:https://stackoverflow.com/questions/56298481/how-to-fix-object-null-prototype-title-product

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