这是我的简单表单:

<form id="loginformA" action="userlogin" method="post">
    <div>
        <label for="email">Email: </label>
        <input type="text" id="email" name="email"></input>
    </div>
<input type="submit" value="Submit"></input>
</form>

这是我的Express.js/Node.js代码:

app.post('/userlogin', function(sReq, sRes){    
    var email = sReq.query.email.;   
}

我试过sReq。query。email或sReq。查询['email']或sReq。params['邮件'],等等。没有一个有用。它们都返回undefined。

当我更改为Get调用时,它可以工作,所以。任何想法?


当前回答

var express        =         require("express");
var bodyParser     =         require("body-parser");
var app            =         express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.get('/',function(req,res){
  res.sendfile("index.html");
});
app.post('/login',function(req,res){
  var user_name=req.body.user;
  var password=req.body.password;
  console.log("User name = "+user_name+", password is "+password);
  res.end("yes");
});
app.listen(3000,function(){
  console.log("Started on PORT 3000");
})

其他回答

特快4用户注意事项:

如果你试着把app.use(express.bodyParser());进入你的应用程序,你会得到以下错误当你试图启动你的Express服务器:

错误:大多数中间件(如bodyParser)不再与Express捆绑,必须单独安装。请参见https://github.com/senchalabs/connect#middleware。

你必须从npm中单独安装包体解析器,然后使用如下代码(示例取自GitHub页面):

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

var app = express();

app.use(bodyParser());

app.use(function (req, res, next) {
  console.log(req.body) // populated!
  next();
})

使用express.bodyParser()的安全问题

虽然目前所有其他答案都建议使用express.bodyParser()中间件,但这实际上是express.json()、express.urlencoded()和express.multipart()中间件(http://expressjs.com/api.html#bodyParser)的包装器。表单请求体的解析由express.urlencoded()中间件完成,这是在req时公开表单数据所需要的全部内容。体对象。

由于express.multipart()/connect.multipart()如何为所有上传的文件创建临时文件(并且不会被垃圾收集)存在安全问题,现在建议不要使用express.bodyParser()包装器,而是只使用所需的中间件。

注意:Connect . bodyparser()将很快更新到只包括urlencoded和json当Connect 3.0发布(Express扩展)。


所以简而言之,与其…

app.use(express.bodyParser());

...你应该使用

app.use(express.urlencoded());
app.use(express.json());      // if needed

如果/当你需要处理多部分表单(文件上传)时,使用第三方库或中间件,如multiparty、busboy、dicer等。

在Express 4.16版编写

在路由器函数中,你可以使用req。属性来访问post变量。例如,如果这是你的表单的POST路由,它会返回你输入的内容:

function(req,res){
      res.send(req.body);

      //req.body.email would correspond with the HTML <input name="email"/>
}

对于那些熟悉PHP的人:为了访问PHP的$_GET变量,我们使用req。为了访问PHP的$_POST变量,我们使用req。Node.js中的body。

如果你想在没有中间件的情况下构建已发布的查询,这可以做到:

app.post("/register/",function(req,res){
    var bodyStr = '';
    req.on("data",function(chunk){
        bodyStr += chunk.toString();
    });
    req.on("end",function(){
        res.send(bodyStr);
    });

});

这将把这个发送到浏览器

email=emailval&password1=pass1val&password2=pass2val

使用中间件可能更好,这样你就不必在每条路由中一遍又一遍地写这个。

来自正式文档版本4

const express = require('express')
const app = express()
app.use(express.json());
app.use(express.urlencoded({ extended: true })) 

app.post('/push/send', (request, response) => {
  console.log(request.body)
})