Nodejs - Req.body 未定义在 post 中,带有快速 4.9.0

Nodejs - Req.body undefined in post with express 4.9.0

本文关键字:Req body 未定义 post Nodejs      更新时间:2023-09-26

我是nodejs的初学者,我尝试使用中间件body-parse或什么都不使用来了解req.body,但两者都发现req.body是未定义的。这是我的代码

var app = require('express')();         
var bodyParser = require('body-parser');
var multer = require('multer');         
app.get('/', function(req, res) {       
    res.send("Hello world!'n");         
});                                     
app.post('/module', function(req, res) {
    console.log(req);                   
    app.use(bodyParser.json());         
    app.use(bodyParser.urlencoded({     
        extended: true                  
    }));                                
    app.use(multer);                    
    console.log(req.body);              
});                                     
app.listen(3000);                       
module.exports = app;  

我使用命令curl -X POST -d 'test case' http://127.0.0.1:3000/module来测试它。

快递版本:4.9.0
节点版本:v0.10.33

请帮忙,谢谢。

默认情况下,

cURL 对不包含文件的表单提交使用Content-Type: application/x-www-form-urlencoded

对于 urlencoding 表单,您的数据需要采用正确的格式:curl -X POST -d 'foo=bar&baz=bla' http://127.0.0.1:3000/modulecurl -X POST -d 'foo=bar' -d 'baz=bla' http://127.0.0.1:3000/module

对于 JSON,您必须显式设置正确的Content-Typecurl -H "Content-Type: application/json" -d '{"foo":"bar","baz":"bla"}' http://127.0.0.1:3000/module

另外,正如@Brett所指出的,您需要在某个地方(路由处理程序之外)在该 POST 路由之前app.use()中间件。

您将body-parser的快速配置放在错误的位置。

var app = require('express')();         
var bodyParser = require('body-parser');
var multer = require('multer');         
// these statements config express to use these modules, and only need to be run once
app.use(bodyParser.json());         
app.use(bodyParser.urlencoded({ extended: true }));                                
app.use(multer);
// set up your routes
app.get('/', function(req, res) {       
    res.send("Hello world!'n");         
});                                     
app.post('/module', function(req, res) {
    console.log(req);                                       
    console.log(req.body);              
});                                     
app.listen(3000);                       
module.exports = app;  

在定义路由之前,必须确保定义所有快速配置。 因为正文解析器负责解析 Requst 的主体。

var express = require('express'),
    app     = express(),
    port    = parseInt(process.env.PORT, 10) || 8080;
//you can remove the app.configure at all in case of it is not supported
//directly call the inner code     
app.configure(function(){
  app.use(bodyParser.urlencoded());
  //in case you are sending json objects 
  app.use(bodyParser.json());
  app.use(app.router);
});
app.listen(port);
app.post("/module", function(req, res) {
  res.send(req.body);
});