'req.body.username' and 'req.body.password' are undefined [duplicate] - node.js

This question already has answers here:
req.body not populating with form data
(2 answers)
Closed 4 years ago.
I am creating login-register system in my project, actually I made it in many of my previous projects but this time I am getting an error, for which I've seen many posts related to this but none of them worked for me.
This is my code:
app.js
const express= require('express');
const mongoose= require('mongoose');
const bodyParser= require('body-parser');
const exphbs= require('express-handlebars');
const path= require('path');
const methodOverride= require('method-override');
const session= require('express-session');
const flash= require('connect-flash');
const app= express();
const port= process.env.PORT || 8000;
mongoose.Promise= global.Promise;
mongoose.connect(process.env.MONGODB_URI ||
'mongodb://localhost:27017/chat',{ useNewUrlParser: true });
app.use(express.static(path.join(__dirname, 'public')));
//body-parser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
//View engine
app.engine('.hbs', exphbs({extname: '.hbs'}));
app.set('view engine', '.hbs');
//Load Routes
const index= require('./routes/index');
//Use routes
app.use('/',index);
app.listen(port,()=> {
console.log(`Started on port ${port}`);
})
routes.index.js
const express = require('express');
const router = express.Router();
const bcrypt= require('bcryptjs');
const {User}= require('../models/User');
router.all('/*',(req,res,next)=> {
req.app.locals.layout= 'layout';
next();
})
router.get('/login',(req,res,next)=> {
res.render('routes_UI/login');
})
router.get('/signup',(req,res,next)=> {
res.render('routes_UI/signup');
})
router.post('/signup',(req,res)=> {
let errors=[];
if(req.body.password!==req.body.confirmPassword){
errors.push({message:'Passwords do not match'});
}
if(errors.length>0){
res.render('routes_UI/signup',{errors});
}else{
User.findOne({ username: req.body.username}).then((user)=> {
if(user){
req.flash('error_message',`A user with this username already exists`);
res.redirect('/signup');
}else{
bcrypt.genSalt(10, function(err, salt) {
bcrypt.hash(req.body.password, salt, function(err, hash) {
const user= new User({
username:req.body.username,
password:hash,
});
user.save().then(()=> {
req.flash('success_message',`You have
registered successfully, please login`);
res.redirect('/login');
});
});
});
}
})
}
})
module.exports = router;
routes_UI.signup.hbs in views folder
<div class="card card-register mx-auto mt-5">
<div class="card-header">Register an Account</div>
<div class="card-body">
<form action="/signup" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="username">Username</label>
<input name="username" class="form-control" id="username" type="text" aria-describedby="username" placeholder="Enter username">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input name="password" class="form-control" id="exampleInputPassword1" type="password" placeholder="Password">
</div>
<div class="form-group">
<label for="exampleConfirmPassword">Confirm password</label>
<input name="confirmPassword" class="form-control" id="exampleConfirmPassword" type="password" placeholder="Confirm password">
</div>
<button type="submit" class="btn btn-primary btn-block">Register</button>
</form>
<div class="text-center">
<a class="d-block small mt-3" href="/login">Login Page</a>
<a class="d-block small" href="/">Home Page?</a>
</div>
</div>
</div>
Error that I obtained is-
(node:2468) UnhandledPromiseRejectionWarning: ValidationError: users
validation failed: username: Path `username` is required., password: Path
`password` is required.
at new ValidationError (C:\Users\DEEPAK\chat-app-
1\node_modules\mongoose\lib\error\validation.js:30:11)
at model.Document.invalidate (C:\Users\DEEPAK\chat-app-
1\node_modules\mongoose\lib\document.js:2064:32)
at p.doValidate.skipSchemaValidators (C:\Users\DEEPAK\chat-app-
1\node_modules\mongoose\lib\document.js:1927:17)
at C:\Users\DEEPAK\chat-app-1\node_modules\mongoose\lib\schematype.js:896:9
at process._tickCallback (internal/process/next_tick.js:61:11)
(node:2468) UnhandledPromiseRejectionWarning: Unhandled promise rejection.
This error originated either by throwing inside of an async function
without a catch block, or by rejecting a promise which was not handled with
.catch(). (rejection id: 1)
(node:2468) [DEP0018] DeprecationWarning: Unhandled promise rejections are
deprecated. In the future, promise rejections that are not handled will
terminate the Node.js process with a non-zero exit code.
User model
const mongoose= require('mongoose');
const UserSchema= new mongoose.Schema({
username:{
type: String,
required: true
},
password:{
type: String,
required: true
}
})
const User= mongoose.model('users', UserSchema);
module.exports={User};
Thanks in advance

//body-parser
app.use(function(req, res, next)
app.use(bodyParser.urlencoded({extended:true}));
The above first line of code is incomplete and unnecessary. To correctly initialize body parser you can simply do the following as pointed out in the documentation.
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())

You're missing the main body-parser directive:
app.use(bodyParser.json())

Related

Can't redirect after Mongoose query

I am trying to create a website with user accounts.
But can't redirect after Mongoose save query in register page.
Here is NodeJS index.js file
const express = require('express')
const app = express();
const cors = require('cors');
const mongoose = require('mongoose');
const CryptoJS = require('crypto-js');
const jwt = require('jsonwebtoken');
const dotenv = require('dotenv');
const User = require('./models/User');
dotenv.config();
app.set('view engine', 'ejs');
app.use(cors());
app.use(express.urlencoded({extended: true}));
app.use(express.json());
app.use(express.static('public'));
app.use(express.static('partials'));
app.use(express.static('images'));
app.use(express.static('assets'));
mongoose.connect(process.env.MONGO_URL)
.then(() => {
console.log('DB is connected');
})
.catch((err) => {
console.log(err);
});
app.post('/register', async (req, res) => {
const newUser = new User({
email: req.body.email,
password: CryptoJS.AES.encrypt(req.body.password, process.env.PASS_SEC).toString()
})
try {
const savedUser = await newUser.save();
res.redirect('/')
} catch (err) {
console.log(err)
}
})
(of course app.get('/') and app.get('/login') exists in my index.js file)
My register page (register.ejs)
<%- include('./partials/header') %>
<div class='container'>
<div class="login">
<h1 class='heading'>Register</h1>
<div class='form-block'>
<form action="/register" method="POST">
<label class='label'>Email</label>
<input class='input' type='email' name='email' placeholder='example#mail.com' required/>
<label class='label'>Password</label>
<input class='input' type='password' name='password' placeholder='********' required/>
<input class='button' type='submit' value='Sign Up' />
</form>
</div>
</div>
</div>
<%- include('./partials/footer') %>
Instead of redirect to main page I get json data of saved User.
How to fix that?

Req.body is empty and also cannot read property path of undefined

My project was working fine till last week and now all of a sudden my post requests are not working . i tried all methods and read other questions of stack overflow but was unable to fix the issue . can some one please help me?
Issue : req.body is undefined and also whenever i try upload a file "cannot read property path of undefined" is the error.
i'm using express middle ware to parse the request body . i also have my form enctype to multipart/form-data..
Code snippet is below :
require('dotenv').config()
const express = require('express');
const app = express();
const router = express.Router();
const session = require('express-session');
const fs = require(`fs`);
const mysql = require(`mysql-await`);
const path = require('path');
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
const multer = require('multer');
const {storage} = require('../cloudinary');
const upload = multer({storage});
const con = mysql.createConnection({
host: "localhost",
user: "root",
password: "Sujanya#1978",
database: "dept"
});
con.connect((err) => {
if (!err) {
console.log("Connected");
}
else {
console.log(err)
}
})
router.get('/naaccircular',(req,res)=>{
(async () => {
let results = await con.awaitQuery('select* from dept.naaccircular;');
res.render('Naac_circular',{Egs : results})
})();
})
router.get('/naaccriteria',(req,res)=>{
(async () => {
flet results = await con.awaitQuery('select* from dept.naaccriteria;');
res.render('Naac_criteria_files',{Fgs : results})
})();
})
router.post('/naacaddcircular',upload.single('circularfile'),(req,res) => {
console.log(req.body);
const n = req.body.circularname;
const d = req.body.circulardate;
const l = req.file.path;
con.connect(function(err){
var records = [n,d,l];
con.query("insert into dept.naaccircular (cirname,cirlink,cirdate)
VALUES (?,?,?)", [n,l,d] , function (err, result, fields){
if (err) throw err;
})
});
console.log(n);
console.log(l);
console.log(d);
res.redirect('/naaccircular');
})
module.exports = router;
style="margin-top:80px; background-color: white;">
<form action="/naacaddcircular" method="POST" class="row g-3 form-container" enctype="multipart/form-data">
<h3 style="text-align: center;">Naac Circular</h3>
<div class="mb-3">
<label for="ii" class="form-label">Name</label>
<input id="ii" name="circularname" class="form-control" type="text" placeholder="Default input"
aria-label="default input example">
</div>
<div class="mb-3">
<label for="jj" class="form-label">Date</label>
<input id="jj" name="circulardate" class="form-control" type="date">
</div>
<div class="input-group mb-2">
<input type="file" class="form-control" name="circularfile"id="inputGroupFile04" aria-describedby="inputGroupFileAddon04"
aria-label="Upload">
<!--<button class="btn btn-outline-secondary" type="button" id="inputGroupFileAddon04">Button</button>-->
</div>
<button type="submit"
class="btn btn-primary position-relative start-50 botttom-0 translate-middle-x">Upload</button>
</form>
</div> ```
The problem is with cloudinary module. I have rectified it, there are no errors in the post method.
Once upload.single() function is removed from the router.post() function I'm able to get the req.body(),

Body parser returning undefined for req.body request (SIMPLE LOGIN for beginner)

So I installed body parser via
npm i install express body-parser
and I wrote a simple code designed to input a user into an array after they complete a registration form.
but when I console.log the user it returns undefined for both email and password
here is the server code
const express = require('express');
const path = require('path');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
const PORT = 3000;
var Users = [{"email":"mike#gmail.com", "password":"456"}];
app.get('/', (req, res) => {
res.render('index.ejs')
})
app.get('/Register.ejs', (req, res) => {
res.render('Register.ejs')
})
app.post('/views/Register.ejs', (req, res) =>
{
const newUser = {
email: req.body.email,
password: req.body.password
};
Users.push(newUser);
res.json(req.body.email);
console.log(Users)
}
)
app.listen(PORT);
here is the html for the register page
<h1>Please Register</h1>
<body>
<form action="/views/Register.ejs" method="POST">
<div class="div">
<label for="email">Enter Email</label>
<input type="email" id="email"for="email" id="email" required>
</div>
<div class="div">
<label for="password">Enter new password</label>
<input type="password" for="password" id="password" required>
</div>
<button type="submit"> Register </button>
</form>
</body>
Only installing body-parser is not enough. You have to put them in the code as middleware.
Top of the code use:
var bodyParser = require('body-parser');
and then use the code in somewhere middle of the code:
app.use(bodyParser.json())

nodejs: express-validator errors undefined in ejs template

I am using ejs engine instead of pug. When I click register button, I got errors undefined in my register view. There was only little chance that I can get the validation messages, but when I click other links and then back to the register page, the same error occurred again.
Here's my code:
app.js
//app.js code
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var passport = require('passport');
var expressValidator = require('express-validator');
var LocalStrategy = require('passport-local').Strategy;
var multer = require('multer');
var upload = multer({dest: './uploads'});
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Handle Sessions
app.use(session({
secret:'secret',
saveUninitialized: true,
resave: true
}));
// Passport
app.use(passport.initialize());
app.use(passport.session());
// Validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(flash());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
user.js
//user.js code
var express = require('express');
var router = express.Router();
var multer = require('multer');
var upload = multer({dest: 'uploads/'});
/* GET users listing. */
router.get('/', function(req, res, next) {
res.render('members', {page_name : 'members'});
});
router.get('/register', function(req, res, next) {
res.render('register', { page_name: 'register' });
});
router.post('/register', upload.single('profileimage'), function(req, res) {
var name = req.body.name;
var username = req.body.username;
var email = req.body.email;
var password = req.body.password;
var password2 = req.body.password2;
if(req.file){
console.log("uploading file");
var profileimage = req.file.filename;
} else{
var profileimage = "noimage.jpg";
}
req.checkBody('name','Name field is required').notEmpty();
req.checkBody('email','Email field is required').notEmpty();
req.checkBody('email','Email is not valid').isEmail();
req.checkBody('username','Username field is required').notEmpty();
req.checkBody('password','Password field is required').notEmpty();
req.checkBody('password2','Passwords do not match').equals(req.body.password);
// Check Errors
errors = req.validationErrors();
//var errors = JSON.stringify(req.validationErrors());
if(errors){
console.log("errors: " + errors);
res.render('register', {errors: errors});
} else{
console.log('No Errors');
res.render("/");
}
});
router.get('/login', function(req, res, next) {
res.render('login', { page_name: 'login' });
});
module.exports = router;
register.ejs
//register.ejs code
<%include layout%>
<div class="container">
<% if(errors){errors.forEach(function(error){%>
<div class="alert alert-danger"><%= error.msg %></div>
<% })} %>
<h4>register</h4>
<form action="/users/register" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleFormControlInput1">Name</label>
<input type="text" class="form-control" name="name" placeholder="John">
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Email address</label>
<input type="email" class="form-control" name="email" placeholder="name#example.com">
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Username</label>
<input type="text" class="form-control" name="username" placeholder="username">
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Password</label>
<input type="password" class="form-control" name="password" placeholder="password">
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Confirm Password</label>
<input type="password" class="form-control" name="password2" placeholder="confirm password">
</div>
<div class="form-group">
<label for="exampleFormControlInput1">Profile Image</label>
<input type="file" class="form-control" name="profileimage" >
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
</div>
Error
ReferenceError: /Users/duanzhen/Documents/web_workspace/12_projects/node_auth/views/register.ejs:5
3| <div class="container">
4|
>> 5| <% if(errors){errors.forEach(function(error){%>
6|
7| <div class="alert alert-danger"><%= error.msg %></div>
8|
errors is not defined
at eval (eval at compile (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/ejs/lib/ejs.js:549:12), <anonymous>:22:8)
at returnedFn (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/ejs/lib/ejs.js:580:17)
at tryHandleCache (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/ejs/lib/ejs.js:223:34)
at View.exports.renderFile [as engine] (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/ejs/lib/ejs.js:437:10)
at View.render (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/view.js:127:8)
at tryRender (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/application.js:640:10)
at Function.render (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/application.js:592:3)
at ServerResponse.render (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/response.js:971:7)
at /Users/duanzhen/Documents/web_workspace/12_projects/node_auth/routes/users.js:12:9
at Layer.handle [as handle_request] (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/router/layer.js:95:5)
at /Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/router/index.js:335:12)
at next (/Users/duanzhen/Documents/web_workspace/12_projects/node_auth/node_modules/express/lib/router/index.js:275:10)
That's because you are trying to access a non existing variable, note that errors variable is only generated and returned to the view if there where validation errors in your form, otherwise it's undefined, that's why in your condition you have to check if errors variable exists, Like this:
if (typeof errors !== 'undefined') { ...
Note: The typeof operator returns a string: the type of the variable, if the variable is not declared it will return undefined
npm uninstall express-validator --save
npm install express-validator#2.20.8 --save
Have a look at my code, it is working
in file 'index.js'
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Home' ,
success:false,
errors:req.session.errors ,
success:req.session.success });
req.session.errors=null;
});
//////////////checking the form validation
router.post('/submit', function(req, res, next) {
req.check('email','Invalid Email Address!!!!!').isEmail();// it's an built in exprexx validator, but we can also write our own
req.check('password','Pssword lenght must be greater than 5!! ').isLength({min:5});
req.check('password','Password is not confirmed!!').equals(req.body.confirmpassword);
var errors=req.validationErrors();
if (errors){
req.session.errors=errors;
req.session.success=false;
}
else{
req.session.success=true;
}
res.redirect('/');
});
module.exports = router;
in file 'index.ejs'
<h1>Fill the form below..</h1><h1></h1>
<h1>It's an example of Express Validator..</h1><h1></h1>
<% if (success) { %>
<h1><span class="badge badge-success">Congrats!! Form validation is secceded!!!</span></h1>
<% } else { %>
<% if (errors) { %>
<div class="alert alert-danger" role="alert">
<h1><span class="badge badge-danger">Errors Occured!! </span></h1>
<% errors.forEach(function(errors) { %>
<h5><%= errors.msg %> </h5>
<% }); %>
</div>
<% } else { %>
<form action="/submit" method="POST">
<div class="form-row">
<div class="col-7">
<input type="email" class="form-control" id="email" placeholder="email" name="email">
</div>
<div class="col">
<input type="password" class="form-control" id="password" placeholder="password" name="password">
</div>
<div class="col">
<input type="password" class="form-control" id="confirmpassword" placeholder="confirmpassword" name="confirmpassword">
</div>
</div>
<h1></h1>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<% } %>
<% } %>
And of course don't forget to add this lines in 'app.js' file:
//adding validator and session
app.use(expressValidator());
app.use(expressSession({secret:'max',saveUninitialized:false,resave:false}));
<% if(locals.errors){locals.errors.forEach(function(error){%>
<div class="alert alert-danger"><%= error.msg %></div>
<% })} %>

why node.js bodyParser always returns 'undefined'?

In 'app.js' I have
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
'index.js' full codes
var express = require('express');
var router = express.Router();
var mysql = require('mysql');
router.get('/', function(req, res, next) {
res.render('index', { title: 'Here' });
});
router.post('/manager', function(req, res, next) {
var connection = mysql.createConnection({
host : 'localhost',
user : req.body.username,
password : req.body.password,
database : 'shops'
});
connection.connect(function(err){
if(!err)
res.render('manager', { title: 'Here' });
else
console.log("Error connecting database ...");
});
});
module.exports = router;
In 'index.html' login form
<form id='login' method='post' action='manager'>
Username<br>
<input id='username' type='text'><br>
Password<br>
<input id='password' type='password'><br>
<input type='submit' value='Login'>
<input type='reset' value='Reset'>
</form>
In index.js line 12-13
req.body.username
req.body.password
Everytime I try to parse data from html form, they return 'undefined'. I'm new to node.js scripting. Am I doing something wrong?
You're missing name attributes on your <input> tags. Add them like:
<form id='login' method='post' action='manager'>
Username<br>
<input id='username' name='username' type='text'><br>
Password<br>
<input id='password' name='password' type='password'><br>
<input type='submit' value='Login'>
<input type='reset' value='Reset'>
</form>

Resources