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

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())引起的;但你可以看到,我把它叫做路线之前。

有线索吗?


当前回答

如果你使用一些外部工具来发出请求,请确保添加头文件:

内容类型:application / json

其他回答

问题得到了解答。但由于它是相当通用和要求。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中,一旦得到正确的结果,就可以使用软件中的代码生成工具来获得相应的代码。按钮</>在右边栏上。你有很多流行语言/库的选择…

最新版本的Express (4.x)将中间件从核心框架中分离出来。如果需要正文解析器,则需要单独安装它

npm install body-parser --save

然后在代码中这样做

var bodyParser = require('body-parser')
var app = express()

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

// parse application/json
app.use(bodyParser.json())

更新2022

你可以用。

app.use (express.json ())

const express = require('express')
const app = express();
const PORT = process.env.PORT || 3001

// Calling the express.json() method for parsing
app.use(express.json())


app.listen(PORT, () => {
    console.log(`============ API Gateway is open at ${PORT} ============= `)
})

Express. json()是Express中内置的中间件函数。此方法用于解析带有JSON有效负载的传入请求,并基于body解析器。

该方法返回只解析JSON并且只查看内容类型头与类型选项匹配的请求的中间件。

表达。json vs bodyParser.json

当我遇到同样的问题时,尽管我知道BodyParser已不再使用 我已经使用了app.use(express.json()) 问题是{对我来说}: 我在放置

app.use (express.json ())

App.use ('api/v1/example', example) =>{涉及路由}

一旦我重新排列这两行;

1 - app.use(express.json())

2 -应用程序(“火/v1/example”,example)

效果很好

我用:

app.post('/', bodyParser.json(), (req, res) => {//we have req.body JSON
});