Link to home
Start Free TrialLog in
Avatar of Bruce Gust
Bruce GustFlag for United States of America

asked on

Why is Postman Not Seeing the Form Fields in Node?

I'm using Postman to build an API in Node. Here's a portion of my Controller:

 const first_name = req.body.first_name;

Easy, enough...

The thing is, I'm getting a message in Postman that says: "TypeError: Cannot read property &#39;first_name&#39; of undefined<br> &nbsp; &nbsp;at exports.postCreate (C:\wamp\www\authentication\controllers\create.js:9:23)"

Here's the way I've got my Postman dynamic set up:

User generated image
Why is Postman not seeing what I'm assuming are my form fields?
Avatar of leakim971
leakim971
Flag of Guadeloupe image

your issue is not the first_name but the req.body because its null
express ? POST ? GET ? app.post ? app.use ?
we've no information about your create.js code
Avatar of Bruce Gust

ASKER

Leak!

You're right and I've been able to make some progress since originally posting this.

Here's what I've got as far as my relevant code:

router...

const express = require("express");
const { check, body } = require("express-validator/check");

const createController = require("../controllers/create");
const User = require("../models/user");

const router = express.Router();

router.post(
  "/authentication/create",
  [
    body("email")
      .isEmail()
      .withMessage("Please enter a valid email.")
      .normalizeEmail(),
    body("password", "Password has to be valid.")
      .isLength({ min: 5 })
      .isAlphanumeric()
      .trim()
  ],
  createController.postCreate
);

console.log(body);
module.exports = router;

Open in new window


controller:

const bcrypt = require("bcryptjs");
const { validationResult } = require("express-validator/check");
const jwt = require("jsonwebtoken");

exports.postCreate = (req, res, next) => {
  console.log(req.body);
  const first_name = req.body.first_name;
  const last_name = req.body.last_name;
  const user_name = req.body.username;
  const dob = req.body.dob;
  const email = req.body.email;
  const password = req.body.password;

  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    res.json({
      message: "form fields are not correct"
    });
    validationErrors: errors.array(); //send the specific errors in case it's needed
    console.log(errors);
  } //incoming values are legit, now we see if the incoming user is already in the database
  else {
    User.findOne({ email: email }) //look to see if user already exists in the database
      .then(user => {
        if (user) {
          res.json({
            message: "user already exists in database"
          });
        } else {
          bcrypt
            .hash(password, 12)
            .then(hashedPassword => {
              const user = new User({
                first_name: first_name,
                last_name: last_name,
                user_name: user_name,
                dob: dob,
                email: email,
                password: hashedPassword
              });
              return user.save();
            })
            .then(result => {
              res.json({
                message: "new user is successfully created"
              });
            })
            .catch(err => {
              res.json({
                message: "something went wrong with the insert query"
              });
            });
        }
      });
  }
};

//the first line is commented out, although you can include it if you want to specify an expiration time
// jwt.sign({ user: user }, superPassword, { expiresIn: "30s" }, (err, token) => {
/*
jwt.sign({ user: user }, superPassword, (err, token) => {
  res.json({
    token: token
  });
});
*/

Open in new window


As of right now, all this is working. But I want to know WHY it's working!

Here are the adjustments I made to my code:

on app.js, I added:

const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

On Postman, I made these changes:

Changed my content type to "application/x-www-form-urlencoded."

After that, I moved forward with the key value pairs on Postman and it worked fine, but I want to know why.

And, I want to understand whether or not I'm going to have to change my code when I push this to PROD.

When this code gets uploaded to the project that I'm working on, it's going to function as an API that's going to be processing incoming data from a form.

In the tutorial I'm been working through, I've been using an .ejs file with HTML form elements, hence my assumption that when I went to use Postman, I would select the "form data" option and I would be duplicating an incoming HTML form.

Apparently not?

Can you explain why the changes I made amounted to a difference and if those changes have to be altered given the fact that in the end I will be using an HTML form?

Thanks!
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
It was the body-parser!

That did the trick!

Thanks!