I am trying to create a Todolist API, which adds a new todo in my todo.js
file using the POST method. This post method is called using jQuery in my client.js
but I am receiving POST 400 errors in the Chrome Console.
My todo
endpoint:
app.post('/api/v1/newtodos', (req, res) => {
if(!req.body.title) {
return res.status(400).send({
success: 'false',
message: 'title is required'
});
} else if(!req.body.description) {
return res.status(400).send({
success: 'false',
message: 'description is required'
});
} else {
return res.status(400).send({
success: 'false',
message: 'somethings wrong?'
})
}
const todo = {
id: db.length + 1,
title: req.body.title,
description: req.body.description
}
db.push(todo);
return res.status(201).send({
success: 'true',
message: 'todo added successfully',
todo
})
});
and the client-side code that calls the POST method using jQuery:
const appendNewDream = function(dream) {
const newListItem = document.createElement("li");
newListItem.innerHTML = dream;
dreamsList.appendChild(newListItem);
$.ajax({
type: "POST",
url: "https://glossy-pruner.glitch.me/api/v1/newtodos",
data: JSON.stringify({
"title": "Test Name",
"description": "Creating test subject to check POST method API"
}),
error: function(e) {
console.log(e);
},
dataType: "json",
contentType: "application/json"
});
};
Project name: glossy-pruner