本文介绍了无法将嵌套对象json发布到node express body解析器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Node,Express和Mongo创建示例REST api。我正在使用bodyParser()中间件来解析表单数据。对于简单的对象,它的工作正常说

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

req.body

  {
name:'test',
年龄:'20'
}

使用复杂对象时

  var user = {
name:'test',
age:'20',
education:{$



$ b

req.body 产生不同的格式,如

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

我想获得与身体中发布的相同的格式,将其保存在数据库中。这是否是正确的方法或任何其他可用的方法?

解决方案

我认为,文档不清楚。我花了几个小时找到它。无论如何..



您应该将body-parser选项更改为 extension:true ,如下所示。

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


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?

解决方案

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

这篇关于无法将嵌套对象json发布到node express body解析器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 17:23