这是我的简单表单:

<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调用时,它可以工作,所以。任何想法?


当前回答

给定某种形式:

<form action='/somepath' method='post'>
   <input type='text' name='name'></input>
</form>

使用快递

app.post('/somepath', function(req, res) {

    console.log(JSON.stringify(req.body));

    console.log('req.body.name', req.body['name']);
});

输出:

{"name":"x","description":"x"}
req.param.name x

其他回答

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

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

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

对于POST和GET请求,我可以使用以下代码找到所有参数。

var express = require('express');
var app = express();
const util = require('util');
app.post('/', function (req, res) {
    console.log("Got a POST request for the homepage");
    res.send(util.inspect(req.query,false,null));
})

来自正式文档版本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)
})

后端:

import express from 'express';
import bodyParser from 'body-parser';

const app = express();
app.use(bodyParser.json()); // add a middleware (so that express can parse request.body's json)

app.post('/api/courses', (request, response) => {
  response.json(request.body);
});

前端:

fetch("/api/courses", {
  method: 'POST',
  body: JSON.stringify({ hi: 'hello' }), // convert Js object to a string
  headers: new Headers({ "Content-Type": "application/json" }) // add headers
});

我一直在寻找这个问题。我遵循了上面所有的建议。Body仍然返回一个空对象{}。在我的情况下,它只是一些简单的html是不正确的。

在表单的html中,确保在输入标签中使用“name”属性,而不仅仅是“id”。否则,将不会解析任何内容。

<input id='foo' type='text' value='1'/>             // req = {}
<input id='foo' type='text' name='foo' value='1' /> // req = {foo:1}

我愚蠢的错误是你的利益。