Undefined when trying to get data from form - node.js

Same code works fine with other application but for some reason won't work in this one
HTML:
<form action="/employees/add" method="POST" enctype="multipart/form-data" >
<div class="form-group">
<label for="first_name">First Name</label>
<input name="first_name" type="text" class="form-control" id="first_name" value="first_name"placeholder="Please enter your first name">
</div>
<div class="form-group">
<label for="last_name">Last Name</label>
<input name="last_name" type="text" class="form-control" id="last_name" value="last_name" placeholder="Please enter your last name">
</div>
</form>
Server.js
app.post('/employees/add', (req, res) => {
data.addEmployee(req.body).then(() =>{
console.log(req.body);
res.redirect('/employees')
});
Output:
Server running 8080
undefined
Of course, when I call addEmployee since req.body is undefined it won't do anything
I tried different app.use(express.static... ) but no luck and here how my folder looks like

Related

Time Out error trying on send request using a Node Express app

I'm learning through a tutorial to create a form that sends data to my local server and I'm getting a time out error. It's my first time working on post requests using a node.js express application and I'm stuck.
This is the handlebars code:
form method="POST" action="send">
<div class="form-row">
<div class="col-md-4 mb-3">
<label for="validationServer01">First name</label>
<input type="text" class="form-control is-valid" id="validationServer01" placeholder="First name" value="Mark" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-4 mb-3">
<label for="validationServer02">Last name</label>
<input type="text" class="form-control is-valid" id="validationServer02" placeholder="Last name" value="Otto" required>
<div class="valid-feedback">
Looks good!
</div>
</div>
<div class="col-md-4 mb-3">
<label for="validationServerUsername">Username</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupPrepend3">#</span>
</div>
<input type="text" class="form-control is-invalid" id="validationServerUsername" placeholder="Username" aria-describedby="inputGroupPrepend3" required>
<div class="invalid-feedback">
Please choose a username.
</div>
</div>
</div>
</div>
<div class="form-row">
<div class="col-md-6 mb-3">
<label for="validationServer03">City</label>
<input type="text" class="form-control is-invalid" id="validationServer03" placeholder="City" required>
<div class="invalid-feedback">
Please provide a valid city.
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationServer04">State</label>
<input type="text" class="form-control is-invalid" id="validationServer04" placeholder="State" required>
<div class="invalid-feedback">
Please provide a valid state.
</div>
</div>
<div class="col-md-3 mb-3">
<label for="validationServer05">Zip</label>
<input type="text" class="form-control is-invalid" id="validationServer05" placeholder="Zip" required>
<div class="invalid-feedback">
Please provide a valid zip.
</div>
</div>
</div>
<div class="form-group">
<div class="form-check">
<input class="form-check-input is-invalid" type="checkbox" value="" id="invalidCheck3" required>
<label class="form-check-label" for="invalidCheck3">
Agree to terms and conditions
</label>
<div class="invalid-feedback">
You must agree before submitting.
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Submit form</button>
</form>
This is the entry point code:
onst express = require ('express');
const bodyParser = require ('body-parser');
const exphbs = require ('express-handlebars');
const nodemailer = require ('nodemailer');
const path = require ('path');
const app = express ();
//View Engine Setup
app.engine ('handlebars', exphbs());
app.set ('view engine', 'handlebars');
//Static Folder
app.use('/public', express.static(path.join(__dirname, 'public')));
//Body Parser Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//route
app.get ('/', (req,res) => {
res.render('contact', {layout:false})
});
//post route for submission
app.post('/send', (req, res) => {
console.log(req.body);
});
app.listen (3000,() => console.log ('Server started...'));
All I'm getting on my server is: {} when I try to submit.
Whenever you send a form value to the server, always add name attribute to your input fields. Otherwise you won't get the request parameters (req.body) in the server side.
name attribute serves as a JSON property in your case. If you don't provide name attribute, the JSON won't get updated with the field values.
Take some time to read this tutorial:
https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_and_retrieving_form_data

why i cant get data from html form using post method?

i have using ejs engine to get and post method.When i use http://localhost:8080/signup, i will get a sigup form where i can input my values. The problem is after submitting the form,i am unable console the value of "req.body". Help me?
app.post('/signup',urlencodedParser,function(req,res){
//console.log(req)
var names = req.body;
console.log(names);
res.end("sigup submitted");
});
app.get('/signup', function(req, res) {///////////signup ejs loading
res.render('signup')
});
<form id="signupForm" enctype="multipart/form-data" method="post" action="">
<div class="container">
<h1>Sign Up</h1>
<p>Please fill in this form to create an account.</p>
<hr>
<label for="name"><b>Company Name</b></label>
<input type="text" placeholder="Company Name" name="name" required>
<label for="email"><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<label for="psw-repeat"><b>Repeat Password</b></label>
<input type="password" placeholder="Repeat Password" name="psw-repeat" required>
<label for="psw-repeat"><b>Address</b></label>
<input type="text" placeholder="Address" name="address" required>
<label>
<input type="checkbox" checked="checked" name="remember" style="margin-bottom:15px"> Remember me
</label>
<p>By creating an account you agree to our Terms & Privacy.</p>
<div class="clearfix">
<button type="button" class="cancelbtn">Cancel</button>
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
Express does come with some body parsers, but if you are using multipart/form-data then answer would be https://github.com/expressjs/multer not
You can even read that https://www.npmjs.com/package/body-parser (aka body-parser) also do not read multipart/form-data as they can be complicated and should be used only when files are sent.

Cannot POST Form in Node

I am trying to post a simple form from a static page to a database and then re-render the page. Right now I am getting a "Cannot Post /Index" error.
Here is my the form code:
<div class="contact-form">
<form action="/index" method="post">
<div class="col-md-6">
<input type="text" class="form-control" placeholder="Name" name="name">
</div>
<div class="col-md-6">
<input type="email" class="form-control" placeholder="Email" name="email">
</div>
<div class="col-md-6">
<input type="tel" class="form-control" placeholder="Phone Number" name="phone">
</div>
<div class="col-md-6">
<input type="text" class="form-control" placeholder="# of Trucks" name="truckNum">
</div>
<div class="col-md-12">
<input type="text" class="form-control" placeholder="Company" name="company">
</div>
<div class="col-md-12">
<input type="text" class="form-control" placeholder="Address" name="address">
</div>
<div class="col-md-12">
<textarea class="form-control" placeholder="Message" rows="4" name="message"></textarea>
</div>
<div class="col-md-8">
<input type="submit" class="form-control text-uppercase" value="Send">
</div>
</form>
</div>
Here is the router code:
app.get("/", function(req, res) {
res.sendFile(path.join(__dirname, "/../public/index.html"));
});
app.post("/", function(req,res){
db.Contact.create({
name: req.body.name,
email: req.body.email,
phone: req.body.phone,
company:req.body.company,
address:req.body.address,
truckNumber:req.body.truckNum
}).then(function(data) {
res.sendFile(path.join(__dirname, "/../public/index.html"));
});
})
};
Change '/index' to '/' in<form action="/index" method="post">.

Register new 'etudiant'

Hello so i want to register a new user called 'etudiant' in my mongodb with a post request with
<form method="post" action="register">
<h1>Create Account</h1>
<div>
<input type="text" class="form-control" placeholder="first_name" required="required" name="first_name"/>
</div>
<div>
<input type="text" class="form-control" placeholder="last_name" required="required" name="last_name"/>
</div>
<div>
<input type="text" class="form-control" placeholder="cin" required="required" name="cin"/>
</div>
<div>
<input type="text" class="form-control" placeholder="adress" required="required" name="adress"/>
</div>
<div>
<input type="text" class="form-control" placeholder="date_naissance" required="required" name="date_naissance"/>
</div>
<div>
<input type="email" class="form-control" placeholder="Email" required="required" name="mail"/>
</div>
<div>
<input type="password" class="form-control" placeholder="Password" required="required" name="pwd"/>
</div>
<div style="margin:auto;">
<center><input type="submit" value="Register"></center>
</div>
</form>
and the controller for this form is
function register (req, res) {
//create etudiant
var etudiant{
first_name:req.body.first_name,
last_name:req.body.last_name,
cin:req.body.cin,
adress:req.body.adress,
username:req.body.username,
email:req.body.email,
pwd:req.body.pwd
}
//use etudiant model to insert/save
var newetudiant = new Etudiant(etudiant);
//save etudiant
newetudiant.save();
//redirect
res.redirect('/');
}
in the console i got this error that i don't find a solution for
my error
i'm sorry i was working 9hours straight i didn't see my error xD
problem solved still if you look at the
newetudiant.save();
it's right but still doesn't save data to the db

How to use same the form for POST and PUT requests using ejs?

What I'm trying to do is the following:
routes
router.route('/new')
.get(function (req, res) {
var method = ''
res.render('users/new.ejs', { method: method });
});
router.route('/edit/:user_id')
.get(function (req, res) {
var method = '<input type="hidden" name="_method" value="put" />'
var user = User.findById(req.params.user_id, function (err, user) {
if(!err) {
return user;
}
});
res.render('users/edit.ejs', {
method: method
});
});
_form.ejs
<form accept-charset="UTF-8" action="/api/v1/users" method="post">
<%- method %>
<div class="field">
<label for="firstName">First Name</label><br>
<input id="firstName" name="firstName" type="text" />
</div>
<div class="field">
<label for="age">Age</label><br>
<input id="age" name="age" type="number" />
</div>
<div class="field">
<label for="annualIncome">Annual Income</label><br>
<input id="annualIncome" name="annualIncome" type="number" />
</div>
<div class="field">
<label for="email">Email</label><br>
<input id="email" name="email" type="text" />
</div>
<div class="field">
<label for="riskTolerance">Risk Tolerance</label><br>
<input id="riskTolerance" name="riskTolerance" type="number" />
</div>
<div class="actions">
<input type="submit" value="Submit">
</div>
</form>
So, I want to do it like in Rails where you can use the same form for both creating and editing a model. So, I wanted to say that it is a PUT request when the form is used for editing.
Is this the appropriate way to do it?
Rather than embedding html in your routing code, you could just use a conditional statement in the ejs template
routes
res.render('users/edit.ejs', {
put: true
});
_form.ejs
<form accept-charset="UTF-8" action="/api/v1/users" method="post">
<%if (put) { %>
<input type="hidden" name="_method" value="put" />
<% } %>
<div class="field">
<label for="firstName">First Name</label><br>
<input id="firstName" name="firstName" type="text" />
</div>
...
</form>

Resources