Using express and mongoose/mongo to create a todo app. Domain model: Authors have reminders.
In my app.js
:
var bodyParser = require('body-parser')
var methodOverride = require('method-override')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}))
app.use(methodOverride('_method'))
my form using handlebars in views/authors/edit.hbs
:
<h2>Edit {{name}}</h2>
<form action="/authors/{{_id}}" method="post">
<input type="hidden" name="_method" value="put">
<label>Name:</label>
<input type="text" name="name">
<input type="submit">
</form>
My routing for the edit view and put request to update author:
app.get("/authors/:id/edit", function(req, res){
AuthorModel.findById(req.params.id, function(err, docs){
res.render("authors/edit", docs)
})
})
app.put("/authors/:id", function(req, res){
console.log("updating")
AuthorModel.findById(req.params.id, function(err, docs){
docs.name = req.body.name
docs.save(function(err){
if(!err){
res.redirect("authors/" + req.params.id)
}
})
})
})
When I inspect the elements in the dev tools I see everything I need to see, but when I go to submit, gives me error CANNOT POST. Create functionality works fine, so my first thought is the method override isn't working. If I change put to POST, everything works great.
If it helps, link to the repo that contains this app
Judging by the documentation, there are two common ways to override the method:
You're using the "old" method of specifying a form variable, which you can still use, but this requires custom logic on the server side.
It seems to me that the easiest way for you to fix this is to use the query string parameter:
<form action="/authors/{{_id}}?_method=put" method="post">