简体   繁体   English

如何通过 Body-parser 获取 post 值 - Express Node.js

[英]How to get post values by Body-parser - Express Node.js

I am using Express 4.11.1, and Body-parser 1.11.0.我正在使用 Express 4.11.1 和 Body-parser 1.11.0。 When I run the following code I am getting following output当我运行以下代码时,我得到以下输出

Please suggest how to get the form value请建议如何获取表单值

Output输出

{}

server.js服务器.js

var express = require('express');
var bodyParser = require('body-parser');

var app = express();
var router = express.Router();

app.use(bodyParser.json(),bodyParser.urlencoded({ extended: true }));
// Routes

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

app.post('/', function(req, res){    
    console.log(req.body);
    res.send(req.body);
    res.sendFile(__dirname + '/index1.html');
});

app.listen(3000,function(){
    console.log("Working on port 3000");
});

index1.html索引1.html

<!doctype html>
<html>
  <body>
<form id="frmTest" name="frmTest" action="http://localhost:3000/" method="post">
  <input type="text" id="mytext" value="sadfsad fsd fsad" />
  <input type="submit" id="mysubmit" />
</form>
  </body>
</html>

To retrieve data on backend side you must just add name to input field要在后端检索数据,您必须将名称添加到输入字段

<!doctype html>
<html>
  <body>
<form id="frmTest" name="frmTest" action="http://localhost:3000/" method="post">
  <input type="text" id="mytext" name="mytext" value="sadfsad fsd fsad" />
  <input type="submit" id="mysubmit" />
</form>
  </body>
</html>
app.post('/', function(req, res){    
    console.log(req.body.**NAMEATTRIBUTE**);
    res.send(req.body);
    res.sendFile(__dirname + '/index1.html');
});

Give your html 'name' attribute.给你的 html 'name' 属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM