【问题标题】:Express: Req.body is undefined after POST requestExpress: POST 请求后 Req.body 未定义
【发布时间】:2016-09-14 01:02:59
【问题描述】:

我在 app.router 之前使用 express.bodyParser(),标题似乎是正确的,但我在 req.body 上仍然未定义:

var app = express();
...

app.use(express.bodyParser());
...
app.use(app.router);

req.headers 的输出是这样的:

{ host: '127.0.0.1:3000',
  connection: 'keep-alive',
  'content-length': '0',
  'cache-control': 'max-age=0',
  accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  origin: 'http://127.0.0.1:3000',
  'user-agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.76 Safari/537.36',
  'content-type': 'application/x-www-form-urlencoded',
  referer: 'http://127.0.0.1:3000/register',
  'accept-encoding': 'gzip,deflate,sdch',
  'accept-language': 'es-ES,es;q=0.8' }

帖子是这样声明的:

app.post('/register/do', function(req, res) {
    ...
    console.log(req.headers);
    console.log(req.body);
    ...
});

我做错了什么?

【问题讨论】:

  • 我给你加 1 是因为我注意到我没有使用 app.use(express.bodyParser());在我的节点应用程序中。完全解决了我的问题!!谢谢!

标签: node.js express


【解决方案1】:

你得到了Content-Length: 0,所以问题出在客户端。您的 Express 代码看起来没问题。

【讨论】:

  • 我不敢相信我没有注意到这一点。我用 JS 搞砸了一些事情,表单没有正确提交数据。谢谢!
  • 别担心,这发生在我们最好的人身上:)
【解决方案2】:

我对此有很多问题..这帮助我解决了问题。

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

var app = express();

// parse application/x-www-form-urlencoded
**app.use(bodyParser.json());**
app.use(bodyParser.urlencoded({ extended: false }));

【讨论】:

    猜你喜欢
    • 2019-07-04
    • 2012-07-03
    • 2023-04-10
    • 2021-01-05
    • 1970-01-01
    • 2018-11-07
    • 2017-11-16
    • 1970-01-01
    • 2021-03-08
    相关资源
    最近更新 更多