How to post data from form in express.js? - node.js

I am trying to make a user registration router in express. The backend seemed to work fine since I verified it using it postman. However, when I tried to add the front end to it(adding form), I got an error saying
{"errors":[{"location":"body","param":"name","msg":"Name is required"},{"location":"body","param":"email","msg":"Please include a valid email"},{"location":"body","param":"password","msg":" Please enter a password with 6 or more characters"}]} Since I included name attribute in each input tag, I could not figure out where is the problem.
Here is some part of my codes.
server.js
app.use('/api/posts', require('./routes/api/posts'));
users.js
router.post(
'/',
[
check('name', 'Name is required')
.not()
.isEmpty(),
check('email', 'Please include a valid email').isEmail(),
check(
'password',
' Please enter a password with 6 or more characters'
).isLength({ min: 6 })
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
errors: errors.array()
});
}
.
.
.
register.handlebars
<form class="form" action="/api/users" method="post">
<div class="form-group">
<input name="name" type="text" placeholder="Name" requried>
</div>
<div class="form-group">
<input name="email" type="email" placeholder="E-mail">
</div>
<div class="form-group">
<input name="password" type="text" placeholder="Password" minlength="6">
</div>
<input type="submit" value="Create account" class="button green-button" />
</form>ss

use body-parser
middleware with express
https://expressjs.com/en/resources/middleware/body-parser.html

Related

Express.js "TypeError: Cannot read properties of undefined" in req.body

`
router.post("/login", (req, res) => {
console.log(req.body.username)
console.log(req.body.password)
res.redirect("/")
})
<body>
<form action="/register" method="post">
<label for="username">
</label>
<input type="text" name="username" placeholder="Username" id="username" required>
<label for="password">
<i class="fas fa-lock"></i>
</label>
<input type="password" name="password" placeholder="Password" id="password" required>
<input type="submit" value="Login">
</form>
</body>
`
I just started learning express but already have a problem and I can't find any fixes. Somehow the req.body variable is undefined in the post. This is going to be a login system. (Sorry for my bad english)
I first tried to do it like here on github: https://github.com/WebDevSimplified/express-crash-course but i still had the "TypeError: Cannot read properties of undefined" error in my console. So I was looking for something else and found this: https://codeshack.io/basic-login-system-nodejs-express-mysql/
My code is based on the codeshack example but I'm still getting the error.
If you want to access body of post request, we need to use express middleware which will parse the body of request and it will attached it under req.body object.
In order to do it we can use express.urlencoded() middleware.
for more information link
router.post("/login",express.urlencoded({ extended: true }) , (req, res) => {
console.log(req.body.username)
console.log(req.body.password)
res.redirect("/")
})
Add middleware before your handlers
app.use(bodyParser.urlencoded({ extended: false }))

Getting an error while saving hidden type data in mongodb database using nodejs

I have got two things in form the first is add a password and the other is id which is no need to enter as it comes from the database directly when I click on add I got an error
Post method is
router.post('/', checkLogin, function (req, res, next) {
var user = localStorage.getItem('loginname');
var add_model = new pass_cat({
password: req.body.catename,
user_id: req.body.id
})
add_model.save(function (err, doc) {
if (err) throw err;
res.render('AddCategory', {
title: 'Password Management System',
user: user,
msg: 'Inserted Successfully'
})
})
});
And the ejs code for the form is
<form action="/add_category" id="EmployeeForm" class="form-horizontal" method="post" role="form">
<input type="hidden" name="id" value="<%= data%>" >
<div class="form-group">
<label for="Username" class="col-md-3 control-label">Add Category Name</label>
<div class="col-md-9">
<input type="text" class="form-control" name="catename" placeholder="Enter Password Category">
</div>
</div>
<div class="form-group">
<label for="User_id" class="col-md-3 control-label">User_id</label>
<div class="col-md-9">
<input type="text" class="form-control" name="userid" value="<%=data[0]._id%>" placeholder="Enter Password Category">
</div>
</div>
<input type="hidden" name="id" value="<%= data%>" >
there is no need of this line in the form, as data you are not setting anywhere, and its value is not defined.

Why CSRF is not working in only POST route While working in the rest of other Post routes?

I am getting the CSRF forbidden error. However CSRF is working fine in the rest of the application like post route of logout, signUp, Signin deleteing anything et c..
But when I perform the post action in only one route `/addProduct" I am getting the error Note that I am generating my CSRF token before routes declaration.
I am attaching the main file code and the front end code of addProduct.
Here is my main file code where I am generating token and including it in all routes
app.use(csrfProtection);
app.use(flash());
// USed to include token and isLoggedIn information to render in every page
app.use((req, res, next) => {
res.locals.isLoggedIn = req.session.isLoggedIn;
res.locals.csrfToken = req.csrfToken();
res.locals.user= req.session.user;
next();
});
// app.use((req, res, next) => {
// // throw new Error('Sync Dummy');
// if (!req.session.user) {
// return next();
// }});
app.use(multer({ storage: fileStorage,fileFilter:fileFilter }).single('image'));
app.use(shopRoute);
app.use(authRoute);
app.use('/admin',adminRoute);
app.use(errorController.get404);
This is the front end code for ADD_Product.ejs. Here I am including hidden input as well... to get CSRF value back to check it...
<form action="<%=path%>" enctype="multipart/form-data" method="POST">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" name="title" value="<%=product.title%>" >
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="text" class="form-control" id="price" name="price" value="<%=product.price%>">
</div>
<div class="form-group">
<input type="file" class="form-control-file" id="exampleFormControlFile1" name="image" value="<%=product.imageUrl%>">
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Description</label>
<textarea class="form-control" id="exampleFormControlTextarea1" rows="3" name="description" value="<%=product.description%>"></textarea>
</div>
<% if (path=="/admin/edit") { %>
<input type="hidden" name="productId" value="<%=product._id%>">
<% } %>
<input type="hidden" name="_csrf" value="<%= csrfToken %>">
<button type="submit" class="btn btn-primary btn-lg center">+ </button>
</form>

why am i getting forbidden error in only one post Route?

i am getting the CSRF forbidden error .
However csrf is working fine in the rest of the application like post route of logout,signUp,Signin deleteing anything e.t.c/.
But when i perform the post action in only one route "/addProduct"
i got the error
Note that i am generating my CSRF token before routes declaration.
I am attaching the main file code and the front end code of addProduct.
here is my main file code where i am generating token and including it in all routes
app.use(csrfProtection);
app.use(flash());
// USed to include token and isLoggedIn information to render in every page
app.use((req, res, next) => {
res.locals.isLoggedIn = req.session.isLoggedIn;
res.locals.csrfToken = req.csrfToken();
res.locals.user= req.session.user;
next();
});
// app.use((req, res, next) => {
// // throw new Error('Sync Dummy');
// if (!req.session.user) {
// return next();
// }});
app.use(multer({ storage: fileStorage,fileFilter:fileFilter }).single('image'));
app.use(shopRoute);
app.use(authRoute);
app.use('/admin',adminRoute);
app.use(errorController.get404);
This is the front end code for ADD_Product.ejs
here i am including hidden input as well...
to get csrf value back to check it...
<form action="<%=path%>" enctype="multipart/form-data" method="POST">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" name="title" value="<%=product.title%>" >
</div>
<div class="form-group">
<label for="price">Price</label>
<input type="text" class="form-control" id="price" name="price" value="<%=product.price%>">
</div>
<div class="form-group">
<input type="file" class="form-control-file" id="exampleFormControlFile1" name="image" value="<%=product.imageUrl%>">
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Description</label>
<textarea class="form-control" id="exampleFormControlTextarea1" rows="3" name="description" value="<%=product.description%>"></textarea>
</div>
<% if (path=="/admin/edit") { %>
<input type="hidden" name="productId" value="<%=product._id%>">
<% } %>
<input type="hidden" name="_csrf" value="<%= csrfToken %>">
<button type="submit" class="btn btn-primary btn-lg center">+ </button>

Node.js form values are always returning 'undefined'

I have seen similar questions, unfortunately I don't have enough rep points to leave a small comment so I have to make a new question.
In my registration form, I am submitting my FirstName and LastName values which are always coming back undefined, which is strange because even if I submit the form with everything empty, these two are the only fields that return undefined. Here is my routes folder
/routes/main.js
router.post('/register', function(req, res){
var firstName = req.body.FirstName;
var lastName = req.body.LastName;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var cpassword = req.body.cpassword;
//Validation
req.checkBody('firstName', 'First name is required!').notEmpty();
req.checkBody('lastName', 'Last name is required!').notEmpty();
req.checkBody('email', 'E-mail is invalid!').isEmail();
req.checkBody('username', 'Username is required!').notEmpty();
req.checkBody('password', 'Password is required!').notEmpty();
req.checkBody('cpassword', 'Passwords do not match!').equals(password);
var errors = req.validationErrors();
if(errors){
res.render('register', {
errors: errors
});
console.log('there are form errors');
console.log(errors);
console.log(firstName);
console.log(lastName);
} else {
console.log('no errors');
}
and the markup
<h2>Student Registration</h2>
<form method="post" action="/register">
<div class="form-group">
<label for="">First Name</label>
<input type="text" class="form-control" placeholder="First Name" name="FirstName">
</div>
<div class="form-group">
<label for="">Last Name</label>
<input type="text" class="form-control" placeholder="Last Name" name="LastName">
</div>
<div class="form-group">
<label for="">Username</label>
<input type="text" class="form-control" placeholder="Username" name="username">
</div>
<div class="form-group">
<label for="">E-mail</label>
<input type="text" class="form-control" placeholder="email" name="email">
</div>
<div class="form-group">
<label for="">Password</label>
<input type="Password" class="form-control" name="password">
</div>
<div class="form-group">
<label for="">Confirm Password</label>
<input type="Password" class="form-control" placeholder="ConfirmPassword" name="cpassword">
</div>
<button type="submit" class="">Register</button>
</form>
What really bewilders me is that I am seeing the first and last name values when I console.log them, but they still have a value of undefined. Any suggestions?
You havea typo in your validation. In your form you are submitting FirstName and LastName, but during validation you are checking for firsName and lastName

Resources