javascript - req.body 在使用 body-parser 时返回 undefined
问题描述
我正在尝试构建一个接收 POST 请求以创建用户的 API,但我的所有req.body
请求都收到未定义的错误。我的应用程序是这样设置的(为简洁起见):
在我的用户路由文件中由 Express Router 调用的用户控制器
/控制器/user.js
userController.addUser = function(req, res) {
let user = new User();
user.username = req.body.username;
user.first_name = req.body.first_name;
user.last_name = req.body.last_name;
user.email = req.body.email;
user.type = req.body.user_type
// This returns undefined as does all other req.body keys
console.log("REQ.BODY.EMAIL IS: " + req.body.email);
}
用户路由文件:
/routes/user.js - 需要上面的用户控制器
router.post('/user/create', userController.addUser);
主应用程序: 所有路由和控制器都按照我的测试工作,除了使用 req.body.* 的地方
index.js - 主应用程序文件
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/api', routes);
我浏览了 Express 文档和无数 StackOverflow 帖子,但都没有运气。如果您需要进一步说明,请告诉我。
解决方案
有时版本更改body-parser
似乎不起作用,在这种情况下只需使用以下内容,这将删除依赖项body-parser
:
router.post('/user/create', (req, res, next) => {
let body = [];
req.on('error', (err) => {
console.error(err);
}).on('data', (chunk) => {
// Data is present in chunks without body-parser
body.push(chunk);
}).on('end', () => {
// Finally concat complete body and will get your input
body = Buffer.concat(body).toString();
console.log(body);
// Set body in req so next function can use
// body-parser is also doing something similar
req.body = body;
next();
});
}, userController.addUser);
推荐阅读
- visual-studio-2017 - 插入新表单和命令按钮以从一种形式转到另一种形式后,按下键不起作用
- c# - 当内容类型响应为 js 时,Restsharp 响应返回 null
- javascript - 使用自定义范围为分页准备数据的最佳方法是什么
- java - 从地图中提取字段数据
变成一个字符串 - python - 将长 xticks 分成 2 行 matplotlib
- html - 具有边框半径的圆角仅影响一侧
- javascript - 使用jquery应用排序后如何对总行求和
- c# - FluentNHibernate:DateTime 的默认精度已更改?
- php - 如何在WordPress的前端输出附件帖子元
- angular - 在 Cordova DeviceReady 事件之后调用 Angular 模块导入