using hbs engin and res.render shows page inside page - node.js

so I have this login page which ask users for 2 inputs, when user enter wrong values, it suppose to show error message (line of text), instead it showed the whole page inside the current page, and the message is shown in this page.
here is my hbs code:
<form action="/loginadmin" method="POST">
<div class="login100-form validate-form p-l-55 p-r-55 p-t-178" >
<span class="login100-form-title">
LogIn تسجيل الدخول
</span>
<div class="wrap-input100 validate-input m-b-16" data-validate="Please enter username">
<input type="text" name="Mobilenumber" id="Mobilenumber" placeholder="Mobile Number رقم الجوال">
<span class="focus-input100"></span>
</div>
<div class="wrap-input100 validate-input" data-validate = "Please enter password">
<input type="password" name="pass" id="pass" placeholder="Password الرقم السري">
<span class="focus-input100"></span>
</div>
</br>
<div class="container-login100-form-btn">
<button type="submit">
Login دخول
</button>
</div>
<p>{{ErrorMessage}}</p> <!-- this supposed to show error message -->
and here is the index.js part:
//to access the page:
router.get('/Loginpage', function(req, res, next){
res.render('/loginpage/index', {ErrorMessage: ''});
});
//form submission:
router.post('/loginadmin', function(req, res, next) {
//take from input:
var mobileValue = req.body.Mobilenumber;
var passwordValue = req.body.pass;
console.log(mobileValue);
console.log(passwordValue);
// database connection to mongo .. removed for simplicity
collection.find({mobile: mobileValue}).toArray(function(err, docs) {
if(!docs.length ){
console.log('mobile is not registered');
res.render("loginpage/index", {ErrorMessage: 'mobile is not registered'});//this part is causing the trouble I don't know why
}else{
//somethingelse//}
});
thanks,

Related

GET not able to handle Redirect in Nodejs

So, I have this POST method in NodeJS that handles the login authentication
// Login logic
app.post("/home", function(req, res){
Item.findOne({EmailID: req.body.emailAddress}, function (err, docs) {
if(req.body.emailAddress === docs.EmailID && hash(req.body.password, docs.Salt) === docs.Password) {
currentUser = docs.FirstName;
console.log("Damn");
res.redirect("dashboard.html");
}
});
});
I can see in the console that "Damn" is printed, but for some reason, the redirect doesn't go to the following GET "dashboard.html" method as it is supposed to go but rather goes to the 404 error function
app.get("/dashboard.html", (req, res)=>{
console.log("here we go again");
Activity.find({}, function(err, foundItems){
res.render("home", {newListItems: foundItems});
});
});
and instead goes to the following 404 function. "here we go again" doesn't print on the console. Any idea on how to make the redirect go to the get function?
app.get("/*", function(req, res){
res.sendFile(__dirname + "/404.html")
});
This is my HTML
<form class="" action="/home" method="post">
<div class="">
<img class ="tent-image"src="assets/images/tent.png" alt width="90" height="72">
<h4 class="company">PASTIME</h4>
<h1 class="h3 mb-3 fw-normal"> Sign in</h1>
<h4 class="h3 fw-normal" style="color: <%= inputcolor %>"> <%= FirstLine %><br /> <%= SecondLine%> </h4>
<label for="inputEmail" class="virtually-hidden"></label>
<input id="inputEmail" name="emailID" class="form-control" placeholder="Email address" required="" autofocus="">
<label for="inputPassword" class="visually-hidden">Password</label>
<input type="password" name="passWORD" id="inputPassword" class="form-control" placeholder="Password" required="">
<div class="checkbox mb-3">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-dark" type="submit">Submit</button>
<p class="mt-5 mb-3 text-muted">© 2021 Pastime</p>
</form>
Please help
try by using
res.redirect("/dashboard.html");

Why isn't my title being inserted into my database?

I'm trying to insert the title from my input form into my caption column in my database and then display it with the post. The image and delete buttons display, however the title does not.
Here is my route in my server.js:
app.post('/newPost', isLoggedIn, uploads.single('inputFile'), (req, res) => {
console.log('On POST route');
// get an input from user
let file = req.file.path;
console.log(file);
cloudinary.uploader.upload(file, (result) => {
console.log(result);
db.post.create({
caption: req.body.title,
image_url: result.url,
userId: req.body.id
})
// Render result page with image
}).then((post) => res.render('index', { image: result.url }));
})
Here is my newPost.ejs which contains the form:
<div class="postSection">
<form action="/" method="POST" enctype="multipart/form-data">
<input type="title" placeholder="Write a Caption:" id="postText">
<input type="file" name="inputFile" id="inputFile">
<input type="submit" class="btn btn-primary" id="postSubmit" value="Post">
</form>
</div>
And, finally here is my index.ejs page in which it will display:
<div>
<% posts.forEach(function(post) { %>
<h1><%= post.caption %></h1>
<img class="images" width="700px" height="500px" src="<%= post.image_url %>" alt="uploaded image">
<form action="/<%= post.id %>?_method=DELETE" method="POST">
<input id="deleteButton" class="btn-danger" type="submit" value="Remove idea" >
</form>
<br>
<% }) %>
</div>
Can anyone spot why the title isn't being inserted into my database and also why it isn't displaying?
One option to debug is console.log the req.body and search for the text you sent as the title.
I think that the title is in req.body.postText or you should add a name tag to your title input and that will be the name in your req.body.
Let me know if this helps!

Submitting a form results to a url segment undefined in NodeJs

I am setting up a simple form submission, when I submit the form the url becomes undefined
This is the view: http://localhost:3000/dashboard/tours/categories
router.get('/tours/categories', function (req, res) {
res.render('agents/tourcategories', {
page_link: 'wishlist'
});
});
This is the form:
<form method="POST" action="/dashboard/tours/categories" >
<div class="box_general padding_bottom">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Category Name</label>
<input type="text" name="categoryname" class="form-control" placeholder="e.g Hiking">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-secondary pull-left" type="button" data-
dismiss="modal">Cancel</button>
<button id="" type="submit" class="btn btn-primary" >Save</a>
</div>
</form>
when I submit the form tne url changes to: `
http://localhost:3000/dashboard/tours/undefined
router.post('/tours/categories',function (req, res) {
console.log("We are here");
const category = new CategoriesDB({
categoryname: req.body.categoryname,
addedby: res.locals.useremail
});
// Save a Customer in the MongoDB
CategoriesDB.save(function (err) {
if(err){
console.log(err);
return;
}else{
res.redirect('/tours/categories');
}
})
});
I realy dont know where the undefined came from, I have checked everything seems to be okay. It keeps popping up in the url everythime i submit the form
`
From the snippets of the code you have posted, It might be because u have not used the middleware
router.all("/dashboard*");
But if u have used that and the GET request is working but not the POST then u will need to post more snippets of your code, mainly the middleware you defined to handle the routes

How to use endpoint inside another endpoint in express node js

I am just stuck in a problem and also don't know whether the question is correct or not.
I am working on a node express js, using ejs templating engine.
I have created certain endpoints (say login(POST) endpoint) which are generic endpoints.
Now I want to create a new application which uses should use these endpoints and render the view according to the result of these endpoints.
Lets say I have a generic endpoint for login
router.post('/user/login', function (req, res) {
var userLoginId = req.body.username;
var currentPassword = req.body.password;
UserLogin.findOne({userLoginId: userLoginId, currentPassword: currentPassword}, function (err, usr) {
if (err) {
console.log('Error in User login');
console.log(err);
res.status(500).type('application/problem+json').send();
} else {
if (!usr) {
console.log('Please enter valid username and password');
res.status(404).type('application/problem+json').send();
} else {
res.type('application/json').status(200).send(usr);
}
}
});
});
And I am using this login.ejs file
<div class="container panel panel-primary">
<h2 class="h2 text-center">Login</h2>
<form class="form-horizontal" name="loginForm" method="post" action="/user/login">
<div class="form-group">
<label for="username" class="col-sm-offset-2 col-sm-2 control-label">UserName</label>
<div class="col-sm-4">
<input type="text" name="username" class="form-control" id="username" placeholder="username">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-offset-2 col-sm-2 control-label">Password</label>
<div class="col-sm-4">
<input type="password" name="password" class="form-control" id="password" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-4">
<button type="submit" class="btn btn-primary btn-">Sign in</button>
</div>
</div>
</form>
</div>
Now I want to use this code and want to login to the system.
If the user login is successful I want to redirect to dashboard page else same login page.
On executing this code the api returns me the JSON response and from this response how can I decide to whether to redirect on dashboard page or login page.
Please help if more input is needed please put a comment.
I would instead of doing a form request to login, do a AJAX request to login and then use something like jQuery to do the AJAX request and response. Alternatively you could do something like the following.
router.get('/login', function(req, res){
res.render('login', {});
})
router.post('/login', function (req, res) {
var userLoginId = req.body.username;
var currentPassword = req.body.password;
UserLogin.findOne({userLoginId: userLoginId, currentPassword: currentPassword}, function (err, usr) {
if (err) {
console.log('Error in User login');
console.log(err);
// res.status(500).type('application/problem+json').send();
res.status(500).render('login', { error : 'Error finding password'})
} else {
if (!usr) {
console.log('Please enter valid username and password');
// res.status(404).type('application/problem+json').send();
res.status(404).render('login', { error : 'Please enter valid username and password'})
} else {
res.redirect('/dashboard');
}
}
});
});
For the login.ejs file i would conditionally render the error.
<!DOCTYPE html>
<html>
<body>
<div class="container panel panel-primary">
<h2 class="h2 text-center">Login</h2>
<%if (locals.error) { %>
<%= error %>
<% } %>
<form class="form-horizontal" name="loginForm" method="post" action="/user/login">
<div class="form-group">
<label for="username" class="col-sm-offset-2 col-sm-2 control-label">UserName</label>
<div class="col-sm-4">
<input type="text" name="username" class="form-control" id="username" placeholder="username">
</div>
</div>
<div class="form-group">
<label for="password" class="col-sm-offset-2 col-sm-2 control-label">Password</label>
<div class="col-sm-4">
<input type="password" name="password" class="form-control" id="password" placeholder="Password">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-4 col-sm-4">
<button type="submit" class="btn btn-primary btn-">Sign in</button>
</div>
</div>
</form>
</div>
</body>
</html>

How to write Mongo query to find data between dates

I want to get data of owner ID which lies between two dates using datePicker.
HTML
<form method="post">
<div class="col-lg-5 col-md-5">
<label>From</label>
<input type="date" class="form-control" ng-model="date.from" name="datefrom" />
</div>
<div class="col-lg-5 col-md-5">
<label>To</label>
<input type="date" class="form-control" ng-model="date.to" name="dateto" /> </div>
<div class="col-lg-2 col-md-2">
<button class="btn btn-primary " ng-click="getleaddate()">Go</button>
</div>
</form>
Node API
apiRoutes.post('/getleaddate', function(req, res){
var token=getToken(req.headers);
var owner=jwt.decode(token, config.secret);
Lead.find({ownerId:owner._id},date:{$gte :new Date(req.body.datefrom), $lte:new Date(req.body.dateto)},function(err, data){
if(err){res.json(err)}
else{
res.json(data);
console.log(data)
}
});
});
Above API is not working because req.body.datefrom and req.body.dateto is undefined
I don't know how to fix it.
please check the function for ng-click="getleaddate()"
Check the network tab on the request and request body sent .
it is working fine for me :
FormData:
datefrom:2017-01-11
dateto:2017-01-04
router.post('/test', function(req, res) {
console.log(req.body);
console.log(req.body.datefrom);
});
Console Output:
{ datefrom: '2017-01-11', dateto: '2017-01-04' }

Resources