【问题标题】:req.body returns undefined while using body-parserreq.body 在使用 body-parser 时返回 undefined
【发布时间】:2018-09-06 20:34:52
【问题描述】:

我正在尝试构建一个接收 POST 请求以创建用户的 API,但我的所有 req.body 请求都收到未定义的错误。我的应用程序是这样设置的(为简洁起见):

Express Router 在我的用户路由文件中调用的用户控制器

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

【问题讨论】:

  • 我们可以看看您的发帖请求吗?
  • 试试console.log(req.body)
  • @sLaks 我这样做了,这就是我发现它未定义的原因。
  • 我不确定两个解析器是否并行工作
  • @crescentfresh 请同时发布您的客户端代码,该代码实际上会发布到您的网络服务器。您可能只是没有在请求中设置任何内容。

标签: javascript node.js express


【解决方案1】:

我的问题是我如何将正文发送到 API 端点。我在 Postman 中使用 form-data 而不是 x-www-form-urlencoded。用户错误

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-10
      • 2021-08-08
      • 1970-01-01
      • 1970-01-01
      • 2019-05-17
      • 2018-01-28
      • 1970-01-01
      相关资源
      最近更新 更多