如何使用 express .node 、 mongoose 和 ejs 删除对象 [英] How can I delete an object using express .node , mongoose and ejs

查看:17
本文介绍了如何使用 express .node 、 mongoose 和 ejs 删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从数据库中删除一个对象时出错,但是,当我使用 Postman 测试我的代码时它可以工作,所以我认为我的 ejs 语法不正确.

I am getting an error deleting an object from the database, however, when I use Postman to test my code it works so I think my ejs syntax is incorrect.

ejs 代码

                    <center> <a class="delete_category_a" href="/halalMunchies/update-category/<%= category._id%>" style="color: red "> Delete </a> </center>

删除路线

    exports.deleteCategory = (req, res, next) => {

    console.log('DELETE  CATEGORY /delete-category');

    const id = req.params.id;
   

    categorySchema.findByIdAndDelete(id)
        .then(result => {
            //res.redirect('/halalMunchies/all-categories');
            res.send(console.log(result));
        })
        .catch(err => {
            console.log(err);
        });

};

浏览器错误

Cannot GET /halalMunchies/delete-category/6187cb11e3b98a7aa70a277a

推荐答案

您当前的代码正在发送一个 GET 请求(它只是一个普通链接),但您的请求处理程序是一个 DELETE 请求.当前代码中的实际 <form> 没有做任何事情,也不是当前操作的一部分.

Your current code is sending a GET request (it's just a plain link), but your request handler is for a DELETE request. The actual <form> in your current code is not doing anything and is not part of the current action.

由于链接或表单都不能直接发送 DELETE 请求,因此您有以下选择:

Because neither a link or a form can directly send a DELETE request, you have these options:

  1. 您可以使用此技术发送表单 POST 并将 Express 配置为自动将其转换为您的 DELETE 请求(使用中间件),因为您无法通过浏览器中的表单提交发送 DELETE.

  1. You can use this technique to send a form POST and configure Express to automatically turn it into a DELETE request for you (using middleware) because you can't send a DELETE via a form submission in a browser.

您可以使用Javascript中的fetch()接口来拦截点击或表单post,并发送上面相同的POST请求,Express会变成DELETE请求.

You can use the fetch() interface in Javascript to intercept the click or form post and send the same above POST request that Express will turn into a DELETE request.

您可以使用Javascript中的fetch()接口拦截点击或表单post,并直接使用Javascript发送DELETE请求.

You can use the fetch() interface in Javascript to intercept the click or form post and send a DELETE request directly using Javascript.

您可以更改您的 Express 路由以期待 POST,然后使用表单提交或发送 POST 的 fetch() 请求.

You can change your Express route to expect a POST and then use either a form submission or a fetch() request that sends the POST.

我会推荐 #1 或 #3.

I would recommend either #1 or #3.

使用fetch()发送DELETE请求的示例代码:

Example code of using fetch() to send a DELETE request:

const url = "/halalMunchies/update-category/<%= category._id%>";

fetch(url, {
    method: "DELETE",
    credentials: "include"
}).then(result => {
   // handle completion here
}).catch(err => {
   // handle error here
});

这篇关于如何使用 express .node 、 mongoose 和 ejs 删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆