这是我的简单表单:

<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

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)
})
app.use(express.bodyParser());

然后对于app.post请求,你可以通过req.body获取post值。{post请求变量}。

适用于Express 4.1及以上版本

因为大多数答案都是使用Express, bodyParser, connect;其中不建议使用多部分。有一种安全的方法可以轻松地发送post多部分对象。

Multer可以用来代替connect.multipart()。

安装包

$ npm install multer

在你的应用中加载它:

var multer = require('multer');

然后,将它与其他表单解析中间件一起添加到中间件堆栈中。

app.use(express.json());
app.use(express.urlencoded());
app.use(multer({ dest: './uploads/' }));

Connect.json()处理application/json

Connect.urlencoded()处理application/x-www-form-urlencoded

multer()处理多部分/表单数据

在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。

表达v4.17.0

app.use(express.urlencoded( {extended: true} ))

app.post('/userlogin', (req, res) => {    

   console.log(req.body) // object

   var email = req.body.email;

}

express.urlencoded

演示的形式

另一个答案