I'm currently making a to-do list using Express and Node.js with MongoDB and Mongoose. I'm trying to update the to-do list so I've tried to use patch however this just changes the data to null. (No error messages shown but the HTTP status code is 400)
router.patch('/:id', ensureAuth, async(req, res) => {
try {
const id = req.params.id;
const updatedTask = await Task.findByIdAndUpdate(id, {
task: req.body.taskbox
})
res.send(result);
} catch (err) {
res.status(400).json({
message: err.message
})
}
})
I'm thinking the error might be to do with the "req.body.taskbox" since console.log(req.body.taskbox) shows "undefined" and console.log(req.body) prints {}. Furthermore, when I hardcode something there, the patch works. (e.g. task: "Clean window" - this would update the task successfully to say "Clean window").
The code below shows where the HTML form is generated:
static addTaskToTable(currentTask) {
const list = document.querySelector('#task-list');
const row = document.createElement('div');
row.innerHTML = `
<div class="row">
<div class="col-md-8">
<form id="task-form-for-${currentTask.taskId}">
<input type="text" name="taskbox" value="${currentTask.task}" />
</form>
</div>
<div class="col">
<form id="edit-for-${currentTask.taskId}">
<p><input type="submit" class="btn btn-sm btn-primary" value="edit" onclick="Store.editTask('${currentTask.taskId}')" /></p>
</form>
</div>
<div class="col">
<form id="delete-form-for-${currentTask.taskId}">
<p><input type="submit" class="btn btn-danger btn-sm delete" onclick="Store.deleteTask('${currentTask.taskId}')" value=" x " /></p>
</form>
</div>
</div>
`;
list.appendChild(row);
}
I loop through the tasks in the database to display them using this function: (This could be another place that could've caused this error maybe?)
static displayTasks(){
Store.getTasksArr().then(taskData => {
let tasks = [];
let i;
taskData.map((currentTasks) => {
tasks.push(currentTasks)
})
tasks.forEach((task) => UI.addTaskToTable(task));
})
}
The fetch request:
static editTask = async(id) => {
const res = await fetch('http://localhost:5500/tasks/' + id, {
method: "PATCH",
});
const json = await res.json();
console.log(json);
}
My get, post, and delete all work fine and for the post, I wrote something very similar so I'm also confused as to why the patch doesn't retrieve the data from the textbox but in the post request it does:
router.post('/', ensureAuth, async(req, res) => {
try {
const task = new Task({
task: req.body.newtask,
user: req.user.id
})
const newTask = await task.save()
res.status(201)
res.redirect('/home')
} catch (err) {
res.status(400).json({
message: err.message
})
}
})
I also have a body-parser middleware already defined:
app.use(express.urlencoded({extended: false}));
app.use(express.json());