如何从 Express (Node.js) 中的表单获取数据 [英] How to get data passed from a form in Express (Node.js)

查看:67
本文介绍了如何从 Express (Node.js) 中的表单获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的客户端中有此表单:

I have this form in my client side:

<form action="game" method="get">
    <input type="text" name="name"/>
    <input type="submit" />
</form>

我的服务器中有这个脚本:

and I have this script in my server:

app.get('/game',function(req,res){
    res.sendfile(__dirname + '/game.html'); 
});

推荐答案

使用 bodyParser.urlencoded() 中间件:

const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));

然后表单值将在 req.body 上:

Then the form values will be on req.body:

app.post('/game', function (req, res) {
    res.render('the_template', { name: req.body.name });
});

设置 { extended: true } 允许 bodyParser 在表单数据中接受类似 json 的数据,包括嵌套对象.例如{ person: { name: Adam } } 使用 javascript 发送,而不是传统 HTML 表单发送的名称值对.如果不需要,可以将扩展值设置为 false.不定义扩展选项(即使用默认设置)显然已被弃用,他们似乎希望您决定是否需要嵌套选项或纯名称值对.

Setting { extended: true } allows the bodyParser to accept json like data within the form data including nested objects. e.g. { person: { name: Adam } } sent using javascript rather than the name value pairs which traditional HTML form send. If you don't need that you can set the extended value to false. Not defining an extended option (i.e. using a default setting) is apparently deprecated and they seem to want you to decide whether you need nested options or plain name value pairs.

如果你希望能够在你的快递服务器中解析一些路由的表单数据和其他路由的json数据,你可以使用:

If you want to be able to parse form data for some routes and json data for others in your express server, you can use:

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: <true|false> }))

urlencoded() 用于 x-www-form-urlencoded 内容类型

urlencoded() for x-www-form-urlencoded content type

  • true - 用于嵌套数据结构
  • false - 用于名称值对
  • true - for nested data structures
  • false - for name value pairs

json() - 用于应用程序/json 内容类型

json() - for application/json content type

注意form/multipart需要不同的body解析器(比如multer)

Note that form/multipart needs a different body parser (such as multer)

更新:修复如果您收到有关 Body-Parser 被弃用的 ExpressJS 错误

替换

app.use(bodyparser.json()); //utilizes the body-parser package
app.use(bodyParser.urlencoded({extended: true}));

通过

app.use(express.json()); // Used to parse JSON bodies
app.use(express.urlencoded()); //Parse URL-encoded bodies

这篇关于如何从 Express (Node.js) 中的表单获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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