I am currently working on creating a basic task tracker using Express, however, I am encountering difficulties in getting the 'delete' button to function properly

Struggling to implement a simple to do list with a "delete" button that doesn't seem to be working? No errors are popping up, but the button remains unresponsive. Various attempts have been made to fix this issue without success. Uncertain whether the problem lies in the form action within the ejs file or the app.delete function in index.js, or perhaps it's a combination of both. Any help would be greatly appreciated!

ejs file:

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>To Do List</title>
</head>

<body>
    <h1>To Do List</h1>
    <form action="/todo" method="post">
        <input type="text" name="task">
        <button>Add</button>
    </form>
    <ul>
        <% for(let c of todos) { %>
            <li>
                <%= c.task %>
                    <form action="/todo/<%=c.id%>?_method=DELETE" method="POST"><button>Delete</button></form>
                    <%= c.id%>

            </li>
            <% } %>

    </ul>
</body>

</html>

index.js file:

const express = require('express');
const app = express();
const path = require('path');
const methodOverride = require('method-override');
const { v4: uuid } = require('uuid');
uuid();

app.use(methodOverride('_method'));
app.use(express.urlencoded({ extended: true }));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

let todos = [
    {
        id: uuid(),
        task: '1st task, testing'
    }
]

//TO DO INDEX
app.get('/todo', (req, res) => {
    res.render('todo', { todos });

})

//CREATE NEW TASK
app.post('/todo', (req, res) => {
    const { task, id } = req.body;
    todos.push({ task, id: uuid() });
    res.redirect('todo')

})

//DELETE TASK
app.delete('/todo/:id', (req, res) => {
    const { id } = req.body;
    todos = todos.filter(c => c.id !== id);
    console.log(todos);
    res.redirect('/todo')
})

app.listen(3000, () => {
    console.log('LISTENING ON PORT 3000')
})

Answer №1

Your express app's delete route is set up using method type DELETE (app.delete(...)), but your html form has the method mentioned as POST

<form action="/todo/<%=c.id%>?_method=DELETE" method="POST">

This mismatch means that express is not accepting it.

HTML forms only allow GET and POST requests, so for delete API calls, you'll need to use fetch api, jQuery, or AJAX.

I'm unsure why _method=DELETE is included in the form action. If you're using Django/jinja on the frontend, it shouldn't be necessary. For other frameworks, this may vary.

To troubleshoot further, open the network tab in your browser's console, click the button, and check the network call to see why the backend isn't responding to it.

Answer №2

PROBLEM RESOLVED

All it took was updating const { id } = req.body; to const { id } = req.params;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting JavaScript CanvasRenderingContext2D states array into a serialized format

Looking for a way to serialize a canvas' state in order to save it to a database for later restoration. Want to store the data as an object rather than a bitmap file. I've tried using .save() and .restore() on the context object, but they only m ...

Any tips or hacks for successfully implementing vw resizing on the :before pseudo-element in webkit browsers?

When using vw sizes on webkit browsers, a well-known bug can occur where they do not update when the window is resized. The typical workaround for this issue has been to employ javascript to force a redraw of the element by reassigning the z-index upon res ...

jQuery - Uh-oh! Looks like there is a syntax error and the

I encountered an issue with my fiddle where I am getting an error message. Any suggestions on how to effectively handle decimals and spaces within the code, specifically when using .split and join() functions, without causing an unrecognized expression e ...

When sending an Axios POST request, a "Network Error" message may be received even when the status code is 200 and there is a valid response

Currently, I am utilizing Vue JS version 2.5 along with Axios: "vue": "^2.5.17", "vue-axios": "^2.1.4", "axios": "^0.18.0", The main issue I am facing involves making a POST call like so: const data = querystring.stringify({ 'email& ...

Discovering ways to verify if an array is empty within JSON data using JMESPath?

I am presenting JSON data that looks like this: [ { "id": "i_1", "name": "abc", "address": [ { "city": [ "city1", "city2" ] }, { "city": [ "city1", "city2" ...

Swinging text using Javascript/JQuery on the edges of a container

I am looking to create a bouncing text effect within a specific div element (#header). The text successfully bounces off the right side, then reverses and hits the left side. However, the issue arises when it reaches the left side and begins moving right a ...

Which comment widget/platform does 9GAG utilize?

I am in the process of developing a new website and I am looking for a comment system to use. The comment system that 9GAG is currently using really catches my eye. Take a look at this random post as an example: Despite searching through their source code ...

Alexa Account Linking - Error: Account linking credentials are not valid

I've been working on setting up an Alexa skill with account linking. After obtaining the Linking Authorization Code and exchanging it for an Access Token, I attempted to input all the necessary parameters: code, access token, and skill ID into the Ale ...

Tips for improving the performance of MongoDB queries in a Node.js environment

I am currently facing an issue with my code running in nodejs where I need to call a MongoDB query with aggregation properties using callbacks. However, the code is not functioning as expected. I want the code to run asynchronously so that once the MongoDB ...

Tips for automatically injecting Models and Services into all Controllers when developing a Node.js application using Express

After working with Sails and enjoying the automatic injection of models and services into controllers, I'm now looking to replicate this feature in my project using the Express framework. It will definitely save us from having to require them at the s ...

Tips for adding multiple elements to the DOM at once

Is it possible to efficiently append elements to the DOM all at once? In the code snippet below, I am adding elements to a root element (tr_next) within a loop. $('.abc').each(function(){ //create element code here var tr_next = $("<tr> ...

The Twitch API is providing inaccurate channel information

Currently facing an issue while working with the Twitch API. When making a GET request to /api.twitch.tv/helix/search/channels?query=[STREAMER_NAME], it seems to be returning the wrong streamer/user. For instance: /api.twitch.tv/helix/search/channels?quer ...

Is the Messenger Bot ignoring random users?

I am facing an issue that I need help explaining. The bot works perfectly when I use it from my own Facebook account. However, when I ask others to use it, the bot does not respond to them, even though I have received a green tick on the pages_messaging a ...

Setting headers in Node using express-http-proxy before proxying data is an effective way to customize

When attempting to proxy to a specific address, I need to set the header of the proxy beforehand. It's like an interceptor for me. Currently, I am using the express-http-library and express with Node.JS. However, my code so far doesn't seem to be ...

Unable to logout with ExpressJS passport-local

After pasting the passport-local app into my own, I noticed something interesting: I managed to successfully log in users, but for some reason, I can't seem to get them logged out. app.get('/logout', function(req, res){ req.logout(); r ...

Using TypeScript with React: Initializing State in the Constructor

Within my TypeScript React App, I have a long form that needs to dynamically hide/show or enable/disable elements based on the value of the status. export interface IState { Status: string; DisableBasicForm: boolean; DisableFeedbackCtrl: boolean; ...

Synchronous execution of functions in Node.js

I need to ensure that func2 is only called after func1 has completed its execution. { func1(); func2();// } However, the issue arises when func1() starts running and func2() does not wait for it to finish. This leads to a runtime error as func2() require ...

Error encountered in ES6 destructuring syntax

Could you please assist me in figuring out what is causing the issue here: var foo = { bar: 1, baz: 2 }; var { bar, baz } = foo; I encountered an error SyntaxError: Unexpected token {. I am using node v5.4.1 and I am unsure if the problem lies wit ...

Guide to using express to render templates

Here is my current configuration: When I start the server and navigate to localhost, it directs me to home.ejs as specified in my front end routing: However, when I attempt to access localhost:3000/posts, the posts template does not get displayed on my i ...

I need help on correctly retrieving the ng-model value in a controller when using it with the contenteditable directive

I've attempted using ng-change, ng-keypress, ng-keyup, and ng-keydown for this issue. Using ng-change, the ng-model value is being updated in the controller but not reflecting on the front end. However, with the other three methods, the value displa ...