我有这个作为我的快速服务器的配置

app.use(app.router); 
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat" }));
app.set('view engine', 'ejs');
app.set("view options", { layout: true });
//Handles post requests
app.use(express.bodyParser());
//Handles put requests
app.use(express.methodOverride());

但是当我在我的路由中请求req.body.something时,我得到了一些错误,指出body是未定义的。下面是一个使用req的路由示例。身体:

app.post('/admin', function(req, res){
    console.log(req.body.name);
});

我读到这个问题是由缺乏app.use(express.bodyParser())引起的;但你可以看到,我把它叫做路线之前。

有线索吗?


当前回答

历史:

早期版本的Express曾经捆绑了许多中间件。bodyParser是附带的中间件之一。当Express 4.0发布时,他们决定从Express中移除捆绑的中间件,并将它们作为单独的包。在安装bodyParser模块后,语法从app.use(express.json())改为app.use(bodyParser.json())。

bodyParser在4.16.0版本中被添加回Express,因为人们希望它像以前一样与Express捆绑在一起。这意味着如果您使用的是最新版本,则不必再使用bodyParser.json()。您可以使用express.json()代替。

对于那些感兴趣的人来说,4.16.0的发布历史在这里,拉请求在这里。

好吧,言归正传,

实现:

你需要加的就是加,

app.use(express.json());
app.use(express.urlencoded({ extended: true}));
app.use(app.router); // Route will be at the end of parser

并删除bodyParser(在新版本的express中不需要)

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

快递公司会处理您的要求。:)

完整的例子是这样的,

const express       = require('express')
const app           = express()

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

app.post('/test-url', (req, res) => {
    console.log(req.body)
    return res.send("went well")
})

app.listen(3000, () => {
    console.log("running on port 3000")
})

其他回答

var bodyParser = require('body-parser');
app.use(bodyParser.json());

这帮了我大忙。

请求头中的Content-Type非常重要,特别是当你从curl或任何其他工具中发布数据时。

确保你使用的是application/x-www-form-urlencoded, application/json之类的,这取决于你的post数据。将此字段保留为空将使Express混淆。

问题得到了解答。但由于它是相当通用和要求。body未定义是一个常见的错误,特别是对于初学者,我发现这是恢复我所知道的关于这个问题的最好地方。


此错误可能由以下原因引起:

1. [服务器端][经常]忘记或误用解析器中间件

您需要使用适当的中间件来解析传入的请求。例如,express.json()以JSON格式解析请求,express.urlencoded()以urlencoded格式解析请求。

const app = express();
app.use(express.urlencoded())
app.use(express.json())

您可以在express文档页面中看到完整的列表

如果在Express中找不到适合请求的解析器(XML、form-data…),就需要为它找到另一个库。例如,要解析XML数据,可以使用这个库 您应该在路由声明部分之前使用解析器中间件(我做了一个测试来确认这一点!)中间件可以在初始化express app后立即配置。 像其他答案指出的那样,bodyParser自express 4.16.0以来就已弃用,您应该像上面那样使用内置中间件。

2. [客户端][很少]忘记随请求一起发送数据

你需要发送数据…

要验证数据是否已随请求一起发送,请打开浏览器的devtools中的Network选项卡并搜索您的请求。

这种情况很少见,但我看到一些人试图在GET请求中发送数据,因为GET请求请求。Body未定义。

3.[服务器和客户端][经常]使用不同的内容类型

Server and client need to use the same Content-Type to understand each other. If you send requests using json format, you need to use json() middleware. If you send a request using urlencoded format, you need to use urlencoded()... There is 1 tricky case when you try to upload a file using the form-data format. For that, you can use multer, a middleware for handling multipart/form-data. What if you don't control the client part? I had a problem when coding the API for Instant payment notification (IPN). The general rule is to try to get information on the client part: communicate with the frontend team, go to the payment documentation page... You might need to add appropriate middleware based on the Content-Type decided by the client part.

最后,给全栈开发者一个建议:)

当遇到这样的问题时,尝试使用一些API测试软件,如Postman。目标是消除客户端部分的所有噪声,这将帮助您正确识别问题。

在Postman中,一旦得到正确的结果,就可以使用软件中的代码生成工具来获得相应的代码。按钮</>在右边栏上。你有很多流行语言/库的选择…

2020年7月更新

express. bodyparser()不再捆绑为express的一部分。你需要在加载前单独安装:

npm i body-parser

// then in your app
var express = require('express')
var bodyParser = require('body-parser')
 
var app = express()
 
// create application/json parser
var jsonParser = bodyParser.json()
 
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
 
// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
  res.send('welcome, ' + req.body.username)
})
 
// POST /api/users gets JSON bodies
app.post('/api/users', jsonParser, function (req, res) {
  // create user in req.body
})

更多信息请看这里

原来是

在定义路由之前必须确定所有的配置。如果这样做,就可以继续使用express.bodyParser()。

举例如下:

var express = require('express'),
    app     = express(),
    port    = parseInt(process.env.PORT, 10) || 8080;

app.configure(function(){
  app.use(express.bodyParser());
});

app.listen(port);
    
app.post("/someRoute", function(req, res) {
  console.log(req.body);
  res.send({ status: 'SUCCESS' });
});

添加表达。Urlencoded ({extended: true})到路由可以解决这个问题。

router.post('/save',express.urlencoded({ extended: true }),  "your route");