0

I'm facing a problem with the post statement Nodejs and until now I couldn't find the solution the error that I get is :

TypeError: Cannot read property 'name' of undefined
    at C:\x\app.js:26:25

and the line app.js:26:25 is this

  const name = req.body.name;

this is my model :

const mongoose = require('mongoose');
const contactSchema = new mongoose.Schema({
    name: {type : String},
    email: {type : String},
    message:{type : String}
});
const contact = mongoose.model("Contact", contactSchema);
module.exports = contact;

and this is my app.post :

app.post("/send", function (req, res) {
  const name = req.body.name;
  const email = req.body.email;
  const message = req.body.message;

  const add = new contact({
      name: name,
      email: email,
      message: message
  }).save(function (err, data) {
      !err ? res.redirect("/success") : console.log("err");
  });
});

this is my html code of the name :

<div class="wrap-input100 rs1-wrap-input100 validate-input" data-validate="Name is required">
                    <span class="label-input100">Your Name</span>
                    <input class="input100" type="text" id = "name" name="name" placeholder="Enter your name">
                    <span class="focus-input100"></span>
                </div>

Any one can help me on this ? Best Regards,

2 Answers 2

1

I don't know if you are using Express, but if you are, make sure in your main app file you enable req.body vars:

const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
Sign up to request clarification or add additional context in comments.

1 Comment

thank you it worked, I didn't notice that I deleted that,
0

Your error message says that req.body is not set when you go for req.body.name. You need a particular middleware setup to get req.body populated from form POSTs.

Like so:

/*  npm install --save body-parser, cookie-parser  */
/* allow handling json and URL-encoded POST document bodies */
const bodyParser = require( 'body-parser' )
app.use( bodyParser.json() )
app.use( bodyParser.urlencoded( { extended: true } ) )

And, while you're in the neighborhood make sure you're handling your cookies.

const cookieParser = require( 'cookie-parser' )
app.use( cookieParser() )

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.