这个问题通常是因为调用body-parser中间件时,没有使用正确的解析器。body-parser支持多种解析器,包括JSON解析器、urlencoded解析器和raw解析器等。在使用时应该选择正确的解析器,并将该解析器作为参数传递给body-parser中间件。
以下是使用body-parser中间件解析JSON数据的示例代码:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.post('/api/test', (req, res) => {
console.log(req.body);
res.send('success');
});
app.listen(3000, () => {
console.log('server start at http://localhost:3000');
});
在上述代码中,我们使用bodyParser.json()
作为参数传递给app.use()
方法,以使用JSON解析器解析请求体数据。当我们发送JSON数据时,req.body
会被正确地解析和输出。
当然,如果发送的数据不是JSON格式,我们需要使用其他解析器或者自定义解析器来解析请求体数据。具体来说,我们可以使用以下代码来解析urlencoded格式的数据:
app.use(bodyParser.urlencoded({ extended: true }));
如果我们需要自定义解析器,则可以使用bodyParser.raw()
方法,并在回调函数中自定义解析逻辑。例如,以下代码将body-parser中间件作为参数传递给Express的raw-body
中间件,并使用自定义的解析器解析请求体数据:
const rawBody = require('raw-body');
app.use((req, res, next) => {
rawBody(req, { length: req.headers['content-length'] }, (err, buf) => {
if (err) return next(err);
req.body = buf.toString().toUpperCase();
next();
})
});
app.post('/api/test', (req, res) => {
console.log(req.body);
res.send('success');
});
这个例子中,我们