简体   繁体   English

router.put 和 router.delete 的 PUT 和 GET 方法不起作用(快速)

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

I'm building a CRUD app.我正在构建一个 CRUD 应用程序。 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.所以我使用方法覆盖来发送 PUT 和 GET 请求。

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.我正在为 mongodb 使用 monk 驱动程序。

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.我搜索了很多地方,当我点击提交按钮时仍然出现找不到网页 (404) 错误。 What am I missing?我错过了什么? The submit button should call the two methods I showed in index.js .提交按钮应该调用我在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.检查您是否导出了 index.js 文件并将其导入到 app.js 中,我认为它应该可以正常工作,但请尝试重新启动服务器并查看它是否有效。 :) :)

The form method and express route doesn't match.表单方法和快速路由不匹配。

The form method for both are POST respectively.两者的表单方法分别是 POST。

However if you look at the express routes the method are PUT and DELETE.但是,如果您查看快速路线,则该方法是 PUT 和 DELETE。

Try changing the routes and test again if it works.尝试更改路线并再次测试是否有效。

I changed router.put and router.delete to router.post .我将router.putrouter.delete更改为router.post

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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