I am not sure what is wrong with my code. I am new to express. app.js list.ejs
I thought I misspelled a variable, but I am unsure what I did wrong. I am making a todo list project using express and node.js and I need to have a remove task option.
My app.js code is:
app.post('/removetask', (req, res) => {
const task = req.body.task;
task.splice(task.indexOf(task), 1);
res.redirect('/');
});
and my list.js used in the browser is:
<form action="/" method="post">
<input type="text" name="newItem" >
<button type="submit">Add</button>
<button formaction="/removetask" type="submit" id="top">Remove</button>
</form>
The primary issue is that you're trying to use the splice method on a variable named task
, which seems to be a string
(as it's coming from the form's input field).
But you need to maintain an array of tasks
to add and remove task
const tasks = [] //array of tasks
app.post('/removetask', (req, res) => {
const taskIndex = tasks.indexOf(req.body.task);
if (taskIndex !== -1) {
tasks.splice(taskIndex, 1);
}
res.redirect('/');
});
With these changes, you will maintain an array of tasks on the server-side and correctly add or remove tasks. The splice method is used to modify the tasks array.