简体   繁体   中英

PUT and GET methods with router.put and router.delete not working (express)

I'm building a CRUD app. I'm stuck on update and delete operation, everything else seems to be working. So I use method-override to send PUT and GET request.

Here's the relevant code:

app.js

const methodOverride = require('method-override');
app.use(methodOverride('_method'));

Here's what I wrote for update and delete. I'm using monk driver for mongodb.

index.js

var router = express.Router();

router.put('/videos/:id', function(req, res){
    var collection = db.get('videos');
    var item = {
        title: req.body.title,
        genre: req.body.genre,
        image: req.body.image,
        description: req.body.desc
    };
    var id = req.params.id;
    collection.update(
    {_id: id}, {
        $set: item
    });
    res.redirect('/videos');
});

router.delete('/videos/:id', function(req, res){
    var collection = db.get('videos');
    collection.remove({"_id" : req.params.id});
    res.redirect('/videos');
});

For delete form

<form action="/videos/<%= video._id %>?_method=DELETE" method="POST">
<button type="submit" class="btn btn-danger">Delete video</button>
</form>

For update form

<form method="POST" action="/videos/<%= video._id %>?_method=PUT">
    <input type="hidden" name="_method" value="PUT">
</form>

I've searched in many places, still get a webpage not found (404) error when I hit the submit button. What am I missing? The submit button should call the two methods I showed in index.js .

Check whether you exported the index.js file and imported it into the app.js, and i think it should work fine but try restarting the server and see if it works. :)

The form method and express route doesn't match.

The form method for both are POST respectively.

However if you look at the express routes the method are PUT and DELETE.

Try changing the routes and test again if it works.

I changed router.put and router.delete to router.post .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM