Can not post the nested object json to node express body parser

ⅰ亾dé卋堺 提交于 2019-12-06 08:13:12

问题


Hi I'm creating sample REST api using Node, Express and Mongo. I'm using bodyParser() middle ware to parse the form data. Its working fine for simple object say

         var user = {
             name:'test',
             age:'20'
         }

req.body produce the same set of format to save it in the mongodb like.

         {
             name:'test',
             age:'20'
         }

When using complex object

         var user = {
                 name:'test',
                 age:'20',
                 education: {
                     institute:"xxx",
                     year:2010
                 }
            }

req.body produce different format something like

           {
                 name:'test',
                 age:'20',
                 education[institute]: "xxx",
                 edcuation[year]:2010
            }

I would like to get the same format which i post in the body to save them in the database. Is this the right approach or any other method available to this?


回答1:


I think, it's not clear on the documenatation. I've spent hours to find it. Anyway..

You should change your body-parser option to extended: true like the below.

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

https://github.com/expressjs/body-parser?_ga=1.163627447.940445150.1418712389#bodyparserurlencodedoptions



来源:https://stackoverflow.com/questions/26711666/can-not-post-the-nested-object-json-to-node-express-body-parser

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