I have been exploring the MERN stack with the help of this guide: https://www.digitalocean.com/community/tutorials/getting-started-with-the-mern-stack.
Currently, I am trying to test a POST API endpoint that is built using express.
The node server is up and running, and I am utilizing Postman to check the functionality of the endpoint.
However, I am facing challenges in formatting the post data properly, as my POST requests are returning errors when sent.
Below is an overview of my API:
const express = require ('express');
const router = express.Router();
const Todo = require('../models/todo');
router.get('/todos', (req, res, next) => {
//this will return all the data, exposing only the id and action field to the client
Todo.find({}, 'action')
.then(data => res.json(data))
.catch(next)
});
router.post('/todos', (req, res, next) => {
if(req.body.action){
Todo.create(req.body)
.then(data => res.json(data))
.catch(next)
}else {
res.json({
error: "The input field is empty"
})
}
});
router.delete('/todos/:id', (req, res, next) => {
Todo.findOneAndDelete({"_id": req.params.id})
.then(data => res.json(data))
.catch(next)
})
module.exports = router;
Here is my Schema structure:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
//create schema for todo
const TodoSchema = new Schema({
action: {
type: String,
required: [true, 'The todo text field is required']
}
})
//create model for todo
const Todo = mongoose.model('todo', TodoSchema);
module.exports = Todo;
While testing with Postman, my URL is "http://localhost:5000/api/todos", and the request body consists of key-value pairs where the key is "action" and the value is "asdf". The result of sending this data is:
{
"error": "The input field is empty"
}
I am seeking guidance on how to correctly format the body data in order to successfully test my POST endpoint. Any assistance would be greatly appreciated!