What is causing the type error in my code?

Viewed 21

I am trying to console.log the input in this sign up form but every time i fill the details and the submit the form then it shows the following error TypeError: Cannot read properties of undefined (reading 'fName')

Kindly let me know the error in my code.

<form action="/" method="POST">
    <img class="mb-4" src="images/mail.jpg" alt="" width="72" height="57">
    <h1 class="h3 mb-3 fw-normal">Signup the Newsletter</h1>
    <div class="form-floating">
      <input type="text" name="fName" class="form-control top"  placeholder="First Name">
 </div>
    <div class="form-floating">
      <input type="text" name="lName" class="form-control middle"  placeholder="Last Name">
    </div>
    <div class="form-floating">
      <input type="email" name="email" class="form-control bottom"  placeholder="name@example.com">

    </div>


    <button class="w-100 btn btn-lg btn-primary" type="submit">Sign in</button>
    <p class="mt-5 mb-3 text-muted">Follow me</p>
  </form>
// const https = require("https");

const bodyParser = require("body-parser");
const request = require("request");

const app = express();
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended:true}));


app.get("/", function(req, res) {
  res.sendFile(__dirname + "/signup.html");
});

app.post("/", function(res, req){
  var firstName = req.body.fName;
  var middleName = req.body.lName;
  var eMail = req.body.email;

  console.log(firstName, middleName, eMail);
});

app.listen(3000, function() {
  console.log("Server is running on Port 3000");
}); ```


1 Answers

I found these errors in your code, check them and it will work fine.

app.use("/public", express.static(path.join(__dirname, 'public'))); // use this for defining your public folder (and don't forget to import path module above).

app.post("/", function(req, res, next){
 var firstName = req.body.fName;
 var middleName = req.body.lName;
 var eMail = req.body.email;
 console.log(firstName, middleName, eMail);
});

Here as you can see in the callback function we get three parameters first will be the request object, second will be the response object and third is optional next object. But in your case you are reading it from response object but it should be from request.

Thanks

Related