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!
Related
I have created a blog site in NodeJS, EJS using mongodb. My problem is my posts show up from my database but I I want to make a change to it, it won't save.
app.js
app.post('/do-edit-post/:postId',(req, res) => {
const requestedPostId = req.params.postId;
Post.updateOne({ _id:requestedPostId }, {$set: {
title: req.body.title,
author:req.body.author,
content:req.body.content
}
}, function (err, result) {
if (err) {
console.log(err);
} else {
console.log("Post Updated successfully");
res.redirect("/admin");
}
});
});
In my editpostID.ejs:
<form class="" action="/do-edit-post" method="post">
<div class="form-group">
<label>Title</label>
<input class="form-control" hidden="<%= post._id %>">
<input class="form-control" text="text" name="postTitle" value="<%= title %>">
<label>Author</label>
<input class="form-control" text="text" name="postAuthor" value="<%= author %>">
<label>Post</label>
<!-- Text area matching the selector specified in the TinyMCE configuration -->
<textarea id="mytextarea" class="form-control" name="postBody" rows="5" cols="30" value=<%- content %>> </textarea>
</div>
<button class="btn btn-warning" type="submit" name="button">Save</button>
</form>
I even tried adding a hidden input field of ._id but it's not saving. What am I missing?
First of all you should add a input name on your hidden input
<form class="" action="/do-edit-post" method="post">
<div class="form-group">
<label>Title</label>
<input class="form-control" type="hidden" value="<%= _id %>" name="postId"> //<-- name added here also you should send the id on input value
<input class="form-control" text="text" name="postTitle" value="<%= title %>">
<label>Author</label>
<input class="form-control" text="text" name="postAuthor" value="<%= author %>">
<label>Post</label>
<!-- Text area matching the selector specified in the TinyMCE configuration -->
<textarea id="mytextarea" class="form-control" name="postBody" rows="5" cols="30" value=<%- content %>> </textarea>
</div>
<button class="btn btn-warning" type="submit" name="button">Save</button>
</form>
Then on node side you can get the id like this
app.post('/do-edit-post/:id',async (req, res) => {
const requestedPostId = req.body.postId; // <-- get the id from the form
await Post.findByIdAndUpdate(requestedPostId , {
title: req.body.title,
author:req.body.author,
content:req.body.content
}).catch(err => {
if (err){
console.log(err)
}else{
console.log("Post Updated successfully");
res.redirect("/admin");
}
})
});
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
I want to update my images on the blog page. but I got an error in the web browser like
Cannot POST /admin/portfolio/609911b1fba77be609396747/edit_cover
here is edit_cover.ejs file code and I use post method to submit images in the database
<%-include('./partials/header')%>
<div class="container-fluid">
<h1 class="text text-primary">Change Porfolio Cover Image Section</h1>
<div class="card shadow mb-4">
<div class="card-header">
<form action="/admin/portfolio/<%=work._id%>/edit_cover" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="exampleFormControlFile1">Cover</label>
<input type="file" name="cover" class="form-control-file" id="exampleFormControlFile1">
</div>
<div class="form-group">
<label for="exampleFormControlFile2">Snaps of Project</label>
<input class="form-control-file" name="images" type="file" id="exampleFormControlFile2" multiple>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success" >Update</button>
</div>
</form>
</div>
<div class="card-body">
<div class="table-responsive">
</div>
</div>
</div>
My router.js file code is here and two lines of code in here one is get request and other is for post
router.get('/admin/portfolio/:id/cover_edit',serverController.isAuthenticated,serverController.portfolio_edit_cover)
router.post('/admin/portfolio/:id/cover_edit',serverController.isAuthenticated,upload.fields([{name: "cover", maxCount: 1},{name: "images", maxCount: 12}]),serverController.portfolio_edit_cover_post)
here is my backend controller and code for images updating
exports.portfolio_edit_cover = async function(req,res){
res.render('server/edit_cover',{
work : await workCollection.findOne({_id: objectId(req.params.id)})
})
}
exports.portfolio_edit_cover_post = function(req,res){
let uploadImages = new Work(req.body, req.files, req.params.id)
console.log(req.files)
uploadImages.up().then((result)=>{
res.redirect('/admin/portfolio',{
work : result
})
}).catch(()=>{
res.send('404')
})
}
and lastly this all about my model codes. in the following code is just for how update my data onto databae
Work.prototype.up = function(){
return new Promise(async(resolve,reject)=>{
await workCollection.updateOne({_id : objectId(this.id)}, {$set :
{
images : this.images
}
}
)
resolve()
})
}
module.exports = Work
in edit_cover.js file it has path like
action="/admin/portfolio/<%=work._id%>**/edit_cover**" and router.js it's like
router.get('/admin/portfolio/:id**/cover_edit**',serverController.isAuthenticated,serverController.portfolio_edit_cover)
router.post('/admin/portfolio/:id**/cover_edit**',serverController.isAuthenticated,upload.fields([{name: "cover", maxCount: 1},{name: "images", maxCount: 12}]),serverController.portfolio_edit_cover_post)
both of these need to have the same path; everything is fine but at last segment, it should be /cover_edit
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
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' }