Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.js delete request

Making a MERN-stack app but the delete request function is not working.
This is the relevant code

When trying to send a delete request with Postman this error shows. I search through some other StackOverflow questions but can't find an answer. In my previous express applications, it has worked like a charm.

Cannot DELTE /api/todos

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Error</title>
</head>

<body>
    <!--This is the error -->
    <pre>Cannot DELETE /api/todos</pre>
    <!--This is the error ^ -->
</body>

</html>

Todos.js


  const express = require('express');
  const uuid = require('uuid');
  const router = express.Router();
  const todos = require('../../Todo');

  router.get('/', (req, res) => {
      res.json(todos);
  });

  router.get('/:id', (req, res) => {
    const found = todos.some(todo => todo.id === req.params.id);

    if (!found) {
      res.status(400).json({ msg: `No meber whit id of ${req.params.id}` });
    } else {
      res.json(todos.filter(todo => todo.id === req.params.id));
    }
  });

  router.post('/', (req, res) => {
    const newEntry = {
      id: uuid.v4(),
      title: req.body.title,
      completed: false,
    };

    if (!req.body.title) {
      res.status(400).json({ msg: `Pleas include title` });
    }

    todos.push(newEntry);
    res.json(todos);
  });

  router.delete('/:id', (req, res) => {
    const found = todos.some(todo => todo.id === req.params.id);

    if (!found) {
      res.status(400).json({ msg: `No meber whit id of ${req.params.id}` });
    } else {
      todos.filter(todo => todo.id !== req.params.id);
      res.json(todos);
    }
  });

  module.exports = router;

like image 924
Christoffer Hennie Avatar asked Feb 11 '26 05:02

Christoffer Hennie


1 Answers

router.delete('/:id', (req, res) requires a parameter id so the real link should be like DELETE /api/todos/{id}, for example /api/todos/3

As I noticed Your request is sent to /api/todos without parameter

like image 187
Davit Avatar answered Feb 13 '26 19:02

Davit



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!