Emil C.
Emil C.

Reputation: 101

req.body.email is undefined

I'm implementing a password reset following a tutorial but running into a problem. My req.body.email is coming back undefined. I have body-parser installed and my other routes are running perfectly.

Here is my code summary:


var express = require('express');
var router = express.Router({ mergeParams: true });
var Kids = require('../models/kid');
var User = require('../models/user');
var async = require('async');
var nodemailer = require('nodemailer');
var crypto = require('crypto');
var middleware = require('../middleware');

router.post('/password_reset', function(req, res, next) {
 function(token, done) {
      User.findOne({ email: req.body.email }, function(err, user) {
          console.log(req.body.email);  <====== Returning and undefined
          console.log(user); <====== Returning as null
        if (!user) {
          req.flash('error', 'No account with that email address exists.');
          return res.redirect('/password_reset');
        }

        user.resetPasswordToken = token;
        user.resetPasswordExpires = Date.now() + 3600000; // 1 hour

        user.save(function(err) {
          done(err, token, user);
        });
      });
    }
});

and my form

<form action="/password_reset" method="POST" >
  <div class="form-group">
    <label for="exampleInputEmail1">Enter your email address</label>
    <input type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email" required>
    
  </div>
  <button type="submit" class="btn btn-warning">Submit</button>
</form>

Upvotes: 0

Views: 952

Answers (1)

Quentin
Quentin

Reputation: 943516

You have two problems:

You aren't submitting any data

Your <input> has no name attribute, so it can't be a successful control.

If you want req.body.email to have data in it then you need to say name="email".

Related to this, you said <label for="exampleInputEmail1"> but id="email". The for attribute needs to match the id of the element it is labelling. Then aria-describedby="emailHelp" needs to match the ID of the element that is labelling the current element … and isn't needed when you have a real <label>.

You aren't parsing the submitted data

See the documentation for req.body:

Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as express.json() or express.urlencoded().

You haven't used any body-parsing middleware.

Your form is submitting urlencoded data (the default) so use express.urlencoded():

router.use(express.urlencoded())

Upvotes: 1

Related Questions