req.body returns empty object on put request - node.js

Im trying to update data by using put request
im using method-override package and multer for file upload
im not able to figure out what is causing the problem because
my post route is working fine where objects are getting stored in database from req.body fields and file is getting uploaded
this is my route:
app.put("/browse/:id", function(req, res){
console.log( req.body); // returns empty object
console.log( req.file); //undefined
})
this is the form
<form action="/browse/<%= book._id %>?_method=PUT" enctype="multipart/form-data" method="POST">
<input value="<%= book.image %>" type="file" name="image" >
<input value="<%= book.title %>" type="text" name="title" required>
<textarea name="desc">
<%= book.description %>
</textarea>
<button class="btn btn-success" type="submit"> Update </button>
</form>

Sorry, i guess just forgot to put the upload.single('image') method in there. That solved it for me.

Related

My form is not correctly taking the route

I have this weird issue and it seems that I can't resolve it.
Whenever I submit my form, it goes to a "double route".
This is my html form.
<form action="eveniment/<%=eveniment._id%>" method="POST" id="modificaeveniment">
<input type="text" placeholder="titlu eveniment" name="titlu" value="<%= eveniment.name %>">
<button class="btn btn-info">Submit</button>
</form>
This is the route:
app.post("/eveniment/:id", function(req, res){ res.send("post route"); }
And I always get the error:
Cannot POST /eveniment/5f1740204a5a2206cc02b5af/eveniment/5f1740204a5a2206cc02b5af
It looks like somehow it doubles the route.
Just add a / at action="eveniment/<%=eveniment._id%>"
<form action="/eveniment/<%=eveniment._id%>" method="POST" id="modificaeveniment">
<input type="text" placeholder="titlu eveniment" name="titlu" value="<%= eveniment.name %>">
<button class="btn btn-info">Submit</button>
</form>```

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>

Not able to update and delete data from mongoose

I am using ejs template, expressjs, and mongoose. not able to update existed data through form while click on edit button and as well not able to delete it . I want to delete when user click a button as well when user click on edit button it show form and allow him to edit. I already wrote get route , it is working fine.
**Update route:**
router.put('/success123' , function (req, res) {
// const id = req.params.id;
Campaign.findById(id)
.then(campaign => {
campaign.Title = req.body.title;
campaign.Description = req.body.Description;
campaign.save().then(updatePost => {
res.render('success123');
});
});
});
**Delete route**
router.delete ('/delete/:id' , function (req, res){
Campaign.findByIdAndDelete(req.params.id)
.then(deletedPost => {
res.render('success');
});
});
I am getting error and cant figure it out . Event it is not showing any error message in my console. both deleting and updating parts not working and i am able to success fully get route while user click on edit campaign button.
My ejs template for update : THIS IS MY EJS TEMPALTE WHERE I AM SENDING UPDATE INFORMATION THROUGH FORM
<div class="row p-4">
<div class="col-md-7">
<form action="/success123" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="title">Title</label>
<input type="text" value="<%=camplist.Title%>" class="form-control" name="title" id="title" placeholder="Enter The Title">
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea value="" name="description" id="description" class="form-control" placeholder="Enter your content here" rows="10"><%=camplist.Description%></textarea>
</div>
<div>
<input class="form-control" name="rules" type="hidden" placeholder="Enter The Title">
<textarea name="rules" id="editor"></textarea>
</textarea>
</div>
<div class="form-group">
<label for="file">Upload Your Banner Image </label>
<input type="file" class="form-control" id="file" name="uploadedFile" accept="image/jpeg, image/jpg, image/png, image/bmp">
</div>
<button class="btn btn-outline-success btn-lg" type="submit">Update Post</button>
</form>
I am getting error and cant figure it out . Event it is not showing any error message in my console. both deleting and updating parts not working and i am able to success fully get route while user click on edit campaign button.

POST request from handlebars form gives 404

I have the following form in my handlebars code:
{{#if contact}}
<form method="POST" action="/contacts/{{contact._id}}">
<input type="text" name="name">
<input type="text" name="phone">
<button>Update Contact</button>
</form>
{{else}}
When the user clicks the button, my browser is redirected to 'localhost:3000/contacts/34634234'
and I get a 404 error.
I checked, and 34634234 is a valid ID.
In my Node routes, I have
router.post('contacts/:id', function(req, res) {
res.render('index');
});
I know res.render('index') works because I've used it in other parts of my code.
However,
Not sure if is because of this, but...
You're missing type="submit" on the button element.
{{#if contact}}
<form method="POST" action="/contacts/{{contact._id}}">
<input type="text" name="name">
<input type="text" name="phone">
<button type="submit">Update Contact</button>
</form>
{{else}}
And you're missing a slash / at the beginning of your route.
router.post('/contacts/:id', function(req, res) {
res.render('index');
});

Resources