node.js - 试图发出删除请求
问题描述
我正在尝试提出删除请求。路由器.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}}
我的代码有什么问题。
解决方案
发现了一些东西。
首先: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。
推荐阅读
- azure - 在说 Quorum 上部署的私有区块链网络中开采的第一个块的块号是多少?
- php - 如果在mysql表中使用num_rows,面向对象的过程找到空字符串,如何显示消息?
- php - 如何从 json_encode 数组响应中获取元素 - Codeigniter
- html - 如何使用角材料保留选项卡状态?
- docker - Ocelot 找不到重新路由文件
- django - Django Model validation based on a field value of another Model
- yaml - OpenAPI:覆盖引用,引用单个字段
- c# - 如何在 asp.net core 3.1 中为每种类型的请求启用 Cors
- wordpress - WordPress htaccess - 限制对文件的访问(有例外)
- docker - 在同一台机器上使用 docker 运行两个 nginx 实例