首页 > 解决方案 > 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 帖子,但都没有运气。如果您需要进一步说明,请告诉我。

标签: javascriptnode.jsexpress

解决方案


有时版本更改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);

推荐阅读