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

后端 未结 8 483
醉话见心
醉话见心 2020-12-15 05:02

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

rout         


        
相关标签:
8条回答
  • 2020-12-15 05:33

    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.

    0 讨论(0)
  • 2020-12-15 05:34

    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?

    0 讨论(0)
  • 2020-12-15 05:34

    I had the same problem. I found out the problem was in my ejs file. I used this:

    <form method="POST">
    

    But with ajax i set the method to post so somehow when i submitted the form it sent an empty Object and the values i gave. When i deleted the method from ejs the problem solved.

    I hope it helps

    0 讨论(0)
  • 2020-12-15 05:41

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

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

    0 讨论(0)
  • 2020-12-15 05:47

    cos the object is based on the Null object. I found the best way to strip this off, eg if you need an exact match for tests is to use:

    const groups = {...match.groups} // remove null object for test comparison
    
    0 讨论(0)
  • 2020-12-15 05:48

    Try this,

    const obj = JSON.parse(JSON.stringify(req.body)); // req.body = [Object: null prototype] { title: 'product' }
    
    console.log(obj); // { title: 'product' }
    

    Happy Coding..!

    0 讨论(0)
提交回复
热议问题