Submitting a form results to a url segment undefined in NodeJs - node.js

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

Related

Update Operation in MongoDB with NodeJs

I am working on a Blog WebSite with CRUD operation I am able to achieve CRD operations but have issues with update One.
Issue:-
When I click on the edit button it opens the compose tab with the textfile loaded successfully but when I click on update it redirects to the home page but nothing Update, Please help me get out from this.
//This is the code for edit & Update Route
app.get("/posts/:postId/edit", (req, res) => {
Post.findById(req.params.postId, (err, post) => {
if (err) {
console.log(err);
} else {
res.render("edit", { post: post });
}
});
});
app.post("/posts/:postId/edit", (req, res) => {
Post.findByIdAndUpdate(
req.params.postId,
{
$set: {
title: req.body.title,
content: req.body.content,
},
},
(err, update) => {
if (err) {
console.log(err);
} else {
console.log("Post Updated");
res.redirect("/");
}
}
);
});
Form for the Edit/Update
//This is the Edit ejs file containing the update form
<form action="/posts/<%=post._id%>/edit/?_method=PUT" method="post">
<div class="mb-3">
<label for="post-title">Title</label>
<input class="form-control" id="post-title" name="postTitle" type="text" placeholder="Input title"
required autocomplete="off" value="<%=post.title%>">
</div>
<div class="mb-3">
<label for="postcontent">Post</label>
<textarea class="form-control text-area" id="postcontent" name="blog" rows="4" cols="50" required
placeholder="Start writing your blog ..............."><%=post.content%></textarea>
</div>
<button class="btn btn-primary publish-btn" type="submit" name="button">Update</button>
</form>
Your error is from the Ejs
You didn’t rename your req.body well to match your incoming data
You were meant to be used title instead of postTitle
And content instead of blog
Just edit your ejs to this and test gee
<form action="/posts/<%=post._id%>/edit/?_method=PUT" method="post">
<div class="mb-3">
<label for="post-title">Title</label>
<input class="form-control" id="post-title" name=“title" type="text" placeholder="Input title"
required autocomplete="off" value="<%=post.title%>">
</div>
<div class="mb-3">
<label for="postcontent">Post</label>
<textarea class="form-control text-area" id="postcontent" name="content" rows="4" cols="50" required
placeholder="Start writing your blog ..............."><%=post.content%></textarea>
</div>
<button class="btn btn-primary publish-btn" type="submit" name="button">Update</button>
</form>
If this answers your question mark it as done

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>

Uploading file to EC2 Web Server from Web Application

I am creating a simple application using Sails.js. What it basically does is it creates a new Item then saves it to the database and uploads the image to S3.
Here's what happens:
When I run my application on my local, it behaves okay. The req.body has contents, and the req.file('item-image') is not empty.
I am running it on EC2 now, and the problem is, the req.body is just an empty object, but the req.file('item-image') is not empty. I've tried different debugging scenarios, see them below:
If I remove the enctype="multipart/form-data" (I know this is needed for file upload, just trying), I get the req.body object that I expect, but as expected, the req.file('item-image') is empty.
I put back the enctype="multipart/form-data" then tried sending the request without the file, I get my expected req.body object.
I included an image on my request, the req.body object is empty, but the req.file('item-image') isn't.
The weirdest part is, when I send my request through postman, all behaves as expected. I'm really lost now, see my code below:
create_event.ejs
<form action=<%= event.createUrl %> method="POST" id="form-item" enctype="multipart/form-data">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="blue bigger">Please fill the following form fields</h4>
</div>
<div class="modal-body overflow-visible">
<div class="row">
<div class="col-xs-12 col-sm-5">
<div class="space"></div>
<input type="file" name="item-image"/>
</div>
<div class="col-xs-12 col-sm-7">
<div class="form-group">
<label for="form-field-username">Name</label>
<div>
<input class="input-large" type="text" id="form-field-username" placeholder="Item Name" name="item-name" />
</div>
</div>
<div class="space-4"></div>
<div class="form-group">
<label for="form-field-username">Description</label>
<div>
<input class="input-large" type="text" id="form-field-username" placeholder="Item Description" name="item-description"/>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-sm" data-dismiss="modal">
<i class="icon-remove"></i>
Cancel
</button>
<button class="btn btn-sm btn-primary" id="save-item">
<i class="icon-ok"></i>
Save
</button>
</div>
</div>
</div>
</form>
create_event.js
$('#save-item').on('click', function(e){
var response = confirm('Are you sure you want to continue saving this item?');
if(response == true) {
$('#form-item').submit();
}
});
AdminController.js
createItem: function(req, res){
console.log('Saving..');
console.log(req.body);
var eventId = req.path.split('/')[4];
req.file('item-image').upload(function callback(error, uploadedFile){
if(error) {
console.log(error);
return res.serverError();
}
console.log(uploadedFile);
s3Helper.upload(uploadedFile[0], function(error, data){
if(error) {
return res.serverError();
}
var item = {
ITEM_ID: uuid.v1(),
EVENT_ID: req.path.split('/')[4],
NAME: req.body['item-name'],
DESCRIPTION: req.body['item-description'],
IMAGE_URL: data.Location
}
EventItem.create(item, function(error, data){
if(error) {
console.log(error);
return res.serverError();
}
console.log('Successfully saved data: ');
console.log(data);
return res.redirect('/admin/events/' + eventId);
});
});
});
},
Thank you!
I found the answer here https://github.com/balderdashy/sails/issues/2508
Apparently, sails.js uses skipper and is sensitive on the order of the input. I just put the file part on the end and it now works.
I'm just confused as to why it works on my local, and not on my ec2 server.

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' }

Reading mongodb to HBS (handlebars) template

I am trying to display data from my mongodb backend to an hbs template by trying to port over this tutorial. I do not get any errors from the server logs or the console in the browser, but I do not get any data represented on the template. Interestingly enough, however, it is generating html markup. Please help me see the issue.
*Note using express framework (and still learning)
app.js:
app.post("/", function(req, res){
res.render("default", {title:"posts", entries:myRoute.getBlogEntries()});
});
myRoute.js:
exports.getBlogEntries = function(res) {
mongo.connect("mongodb://localhost:27017/myDB", function(err, db){
if(err) { return console.dir(err); }
var collection = db.collection("posts");
collection.find({},{},function(e,docs){
res.render("default", {
"entries" : docs
});
});
});
};
hbs template:
{{#each entries}}
<form method="POST">
<div class="well">
<div class="row">
<div class="col-md-1">
<div>
<button type="submit" value="{{_id}}" class="btn btn-lrg btn-primary" name="voteup" title="Vote post up"><span class="glyphicon glyphicon-thumbs-up"></span></button>
</div>
<div style="text-align:center;padding-right:5px;padding-top:7px;padding-bottom:7px;"><span class="badge">{{voteCount}}</span></div>
<div>
<button type="submit" value="{{_id}}" class="btn btn-lrg btn-danger" name="votedown" title="Vote post down"><span class="glyphicon glyphicon-thumbs-down"></span></button>
</div>
</div>
<div class="col-md-10">
<h4>{{title}}</h4>
<label style="font-weight:normal;font-style:italic">Posted: {{published}}</label>
<div>
{{body}}
</div>
</div>
</div>
</div>
</form>
{{/each}}
Thanks in advance!
I assume you are using the mongodb driver,which you did not specify.
collection.find returns a mongodb cursor , not an array of documents. You can use toArray to get the documents :
collection.find().toArray(function(e,docs){
...
}
I suggest your read the documentation of the library before using it,because you just can guess what an api does.

Resources