Adil
Adil

Reputation: 55

Trying to make delete request

I am trying to make delete request. router.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 file

<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}}

Whats wrong with my code.hfjsdkfhjskdfhjskdfhsjkdfhjsdkhfjksfhkjsdfhjksdfhjksdfhjksdfhjskdfhsjkdfhjksdhfjksd sfdjfjksdlfjkdlsfsd fdskljflkjsdfkljdslfjsdl fsdjdkshfjkdshfkjsf sfhsjfkhjksdfksd

Upvotes: 0

Views: 311

Answers (2)

gian.gyger
gian.gyger

Reputation: 173

Found a couple of things.
First: Model.findById is asynchronous and you don't need the new keyword.

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

Second: In order to remove the right item, you actually need to pass the id, not the whole object. And I would use Model.findOneAndDelete instead of Model.remove.

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

But you can do all of this in one step:

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

Edit: You can also not use DELETE in HTML form submissions. Use POST and change your route to POST too.

Upvotes: 1

Rehan Sattar
Rehan Sattar

Reputation: 3945

The reason is that the method attribute of form tag does not accepts any other method than POST & GET.

Try to use some request api like fetch or change the method to POST from DELETE on both front end and backend side.

Reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#attr-formmethod

Upvotes: 0

Related Questions