在使用BodyParser解析请求体时,如果返回一个空对象,可能是因为请求体为空或解析出错。以下是一种可能的解决方法:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
// 使用JSON格式的请求体
app.use(bodyParser.json());
// 使用urlencoded格式的请求体
app.use(bodyParser.urlencoded({ extended: true }));
// 其他中间件和路由处理程序...
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
app.post('/example', (req, res) => {
console.log(req.body); // 打印请求体的值
// 其他处理逻辑...
});
body-parser
库的json()
方法,则请求头应该包含Content-Type: application/json
。如果上述方法仍然无法解决问题,可以尝试使用其他的请求体解析库,如multer
或formidable
。