简体   繁体   中英

req.body returns undefined while using body-parser

I'm trying to build an API that receives a POST req to create a user but I am getting undefined errors for all of my req.body requests. My app is set up like this (simplified for brevity):

User controller that gets called by Express Router in my user routes file

/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);
} 

User Route File:

/routes/user.js - requires user controller above

router.post('/user/create', userController.addUser);

Main App: all routes and controllers work per my tests except where req.body.* is used

index.js - main app file

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.use('/api', routes);

I have looked through the Express documentation and through countless StackOverflow posts with no luck. Let me know if you need further clarification.

My issue was how I was sending the body to the API endpoint. I was using form-data instead of x-www-form-urlencoded with Postman. User error

Sometime with change in version body-parser seems to not work, in that case just use following, this will remove dependency from 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM