I created a to-do list with nodeJS and mongoDB
So far I can display the data from mongodb and I can POST new items from my form. However, when I try to delete items from my to-do list I get a 404 status. Adding to that I get the following message in the console:
"JSON.parse: unexpected character at line 1 column 1 of the JSON data" I am not sure if that is related.
I hoped it was something simple like the url path in my 'main.js' being wrong, but that is not the issue since I created a separate html to check the path from within the same location. ("fetch('../../views/todoParents/' + task......")
My ejs file with the html code (todoParents.ejs) / only part of it :
<h1>Time to burden the children</h1>
<ul id="taskList">
<% for(var i=0; i < tasks.length; i++) { %>
<li class="task-item<%=[i] %>">
<span class="task-info"> <%= tasks[i].item %> </span>
<span class="delete">Delete</span>
</li>
<% } %>
</div>
<script src="../public/assets/main.js"></script>
My main.js file
let taskList_Ul = document.getElementById('taskList');
taskList_Ul.addEventListener('click', function(e) {
e.preventDefault();
let clickedElement = e.target;
let content_clicked_Sibling = clickedElement.previousElementSibling.textContent;
let task = content_clicked_Sibling.replace(/ /g, "");
console.log(task)
fetch('/todoparents/' + task, {
method: 'DELETE',
headers: {'Content-Type': 'application/json'}
}).then(console.log)
.then(res => res.json()
.then(data => {
return data;
})
);
});
app.js with all controllers
let express = require('express');
let app = express();
let bodyParser = require('body-parser');
let mongoose = require('mongoose');
mongoose.connect('online-connection to MongoDB);
let taskSchema = new mongoose.Schema ({
item: String
})
app.use(bodyParser.urlencoded({extended: true}));
app.set('view engine', 'ejs');
app.use(express.static('./'));
//name of my collection in mongoDB
let Task = mongoose.model("Tasks", taskSchema);
app.get('/todoParents', function(req, res) {
Task.find({}, function(err, tasks) {
if (err) {
} else {
res.render('todoParents', {tasks : tasks})
}
});
});
//// some more code, but not included (post method)
// probably where the problem lies...?
app.delete('todoparents/:task', function (req, res) {
//delete the requested item form mongodb
Task.find({task: req.param.task.replace(/\-/g,"")}).remove()(function (err, data) {
if (err) throw err;
res.json(data)
});
});
let port = 3333;
app.listen(port);
Example of item in mongoDB
{"_id":{"$oid":"5db5ed0a060ad747ac79b5b4"},
"item":"do some more stuff",
"__v":{"$numberInt":"0"}}
Here is the folder structure: