首页 > 解决方案 > 试图发出删除请求

问题描述

我正在尝试提出删除请求。路由器.js

const { Router } = require("express");
const Todo = require("../models/todo");
const router = Router();

router.get("/", async (req, res) => {
const todos = await Todo.find({}).lean();

res.render("index", {
    title: "Todo App",
    todos
});
});

router.post("/create", async (req, res) => {
const todo = new Todo({
    title: req.body.title
})

await todo.save();
res.redirect("/");
});

router.delete("/deltodo", async (req, res) => {
const todo = new Todo.findById(req.body.id);

const removetodo = await Todo.remove({_id: todo});
res.json(removetodo);
res.redirect("/");
})

module.exports = router;

.html 文件

<h2>Todo Page</h2>

<form action="/create" method="POST">
<div class="input-field">
    <input type="text" name="title">
    <label>Todo title</label>
</div>
<button type="submit" class="btn">Create</button>
</form>
{{#if todos.length}}
<ul>
{{#each todos}}
<li class="todo">
    <form action="/deltodo" method="DELETE">
        <label>
            <span>{{title}}</span>

            <input type="hidden" value="{{_id}}" name="id">

            <button class="btn btn-small" type="submit">Delete</button>
        </label>
    </form>
</li>
{{/each}}
</ul>
{{else}}
<p>NO TODOS</p>
{{/if}}

我的代码有什么问题。

标签: node.jsmongodbexpress

解决方案


发现了一些东西。
首先:Model.findById是异步的,你不需要new关键字。

const todo = await Todo.findById(req.body.id);

第二:为了删除正确的项目,您实际上需要传递 id,而不是整个对象。我会使用Model.findOneAndDelete而不是Model.remove

const removetodo = await Todo.findOneAndDelete({_id: todo._id});

但是您可以一步完成所有这些:

await Todo.findOneAndDelete({_id: req.body.id});

编辑:您也不能在 HTML 表单提交中使用 DELETE。使用 POST 并将您的路线也更改为 POST。


推荐阅读