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

查看:96
本文介绍了如何从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'); 
});

plss help。

plss help.

推荐答案

使用 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() - 对于application / json内容类型

json() - for application/json content type

请注意,form / multipart需要一个不同的主体解析器(例如multer)

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

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

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