javascript - 如何从 Express (Node.js) 中的表单获取数据

标签 javascript node.js express

我想获取使用表单从页面传递的数据,并在重定向的页面中使用该数据。

我的客户端有这个表格:

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

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

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 上:

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

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

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

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

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

  • true - 用于嵌套数据结构
  • false - 用于名称值对

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

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

更新:修复 ExpressJS 关于 Body-Parser 被弃用的错误

替换

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

关于javascript - 如何从 Express (Node.js) 中的表单获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9304888/

相关文章:

javascript - 排序前解析字段函数

javascript - AngularJS 服务的问题

javascript - Object.assign 和 just assign 的区别

javascript - 未捕获的语法错误 : Unexpected token }

javascript - 如何在nodeJs中为单词着色

javascript - 如何发送数字框表情符号 (1️⃣)?

javascript - '未捕获的语法错误 : Unexpected token <' in Node. js

javascript - 如何将 MongoDB/Express Router 文件与客户端 javascript 文件进行交互

javascript - 如何在字符串中的数字中添加逗号

javascript - 生成不会改变的虚假数据