如何在express.js中嵌套表单数据? [英] How to get nested form data in express.js?

查看:98
本文介绍了如何在express.js中嵌套表单数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 < p>在Rails中,如果您有一个带有下划线的表单,它将在params中采用嵌套的布局结构: input type =textname =person_first/> 
< input type =textname =person_last/>

在服务器上,您将得到:

  params#=> {person:{first:Tom,last:Hanks}} 

当我在node.js中使用Express.js,bodyparser似乎并没有做同样的事情。看看bodyparser的代码,它只是运行JSON解析器,导致:

  params#=> {person_first:Tom,person_last:Hanks}} 

有没有办法可以得到嵌套表单数据,像在Rails中,当我使用Express?有没有可以让我这样做的图书馆?

解决方案

如果你使用 express.bodyParser 可以使用数组表示法传递嵌套数据。



添加 express.bodyParser 你的控制器。

  app.use(express.bodyParser()); 

现在您可以在html代码中使用此符号:

 < input type =textname =person [first]/> 
< input type =textname =person [last]/>

 < input type =textname =person [name] [first]/> 
< input type =textname =person [name] [last]/>



Express 4的更新



这里是设置 extension:true

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


In Rails, if you have a form with underscores, it will assume a nested layout structure in params:

<input type="text" name="person_first" />
<input type="text" name="person_last" />

On the server, you'll get:

params #=> { person: { first: "Tom", last: "Hanks" } }

When I'm using Express.js in node.js, bodyparser doesn't seem to do the same thing. Looking at the code for bodyparser, it just runs the JSON parser on it, resulting in:

params #=> { person_first: "Tom", person_last: "Hanks" } }

Is there some way I can get the nested form data, like in Rails, when I'm using Express? Is there a library that enables me to do this?

解决方案

If you are using express.bodyParser you can use array notation to pass nested data.

Add express.bodyParser middleware before your controllers.

app.use(express.bodyParser());

Now you can use this notation in your html code:

<input type="text" name="person[first]" />
<input type="text" name="person[last]" />

or

<input type="text" name="person[name][first]" />
<input type="text" name="person[name][last]" />

Update for Express 4

The key here is setting extended: true

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

这篇关于如何在express.js中嵌套表单数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆