我有一个 html,其中有 4 个输入字段。表单配置如下:
<form action="/" method="post" onsubmit="alert('data submittet')">
因此,它应该默认为 x-www-form-urlencoded。 该表格正在运行,我可以提交我的数据。
在服务器/node.js 端我有以下配置和代码:
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true
}));
app.post("/", function (req, res, next) {
console.log(req.body);
console.log(req.body.var1);
console.log(typeof(req.body.var1));
});
我从中得到的是控制台窗口中花括号中的实际值:
{ var1: '123456', text1: 'oiu', text2: 'abc', text3: 'def' }
但我无法控制台记录各个参数,因为它们是“未定义的”,而且我不明白如何获取这些值,因此我可以在服务器端的代码中使用它们。我是否缺少某些解析器、设置或为什么这不起作用?
最佳答案
哎呀。它只是将 req.body 数据存储在一个变量中 :S
app.post("/", function (req, res, next) {
console.log(req.body);
var receiveddata = req.body;
console.log(receiveddata.var1);
})
关于javascript - 如何检索数据/ key :value pairs from URL-encoded form using POST in express/node. js?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56642661/