在使用 body-parser 解析请求体时,可以通过设置 type 参数来指定要解析的请求体的类型。但是有时候 body-parser 会忽略 type 参数,导致解析出错。
以下是一个解决方法的示例代码:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// 解析 application/json 类型的请求体
app.use(bodyParser.json());
// 解析 application/x-www-form-urlencoded 类型的请求体
app.use(bodyParser.urlencoded({ extended: false }));
// 自定义中间件,用于解析 text/plain 类型的请求体
app.use((req, res, next) => {
if (req.is('text/*')) {
req.text = '';
req.setEncoding('utf8');
req.on('data', (chunk) => {
req.text += chunk;
});
req.on('end', () => {
next();
});
} else {
next();
}
});
// 路由处理程序
app.post('/', (req, res) => {
console.log(req.body); // 输出请求体内容
res.send('Success');
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
在上面的示例代码中,我们首先使用 bodyParser.json()
和 bodyParser.urlencoded()
中间件来解析 application/json 和 application/x-www-form-urlencoded 类型的请求体。
然后,我们添加了一个自定义的中间件,用于解析 text/plain 类型的请求体。这个中间件判断请求类型是否为 text/*,如果是的话,就以文本形式解析请求体,并将解析后的文本保存在 req.text
中。
最后,我们添加了一个路由处理程序,用于处理 POST 请求。在处理程序中,我们可以通过 req.body
访问解析后的请求体内容。