0

I am following: https://www.digitalocean.com/community/tutorials/getting-started-with-the-mern-stack.

I would like to test an API endpoint built using express. I would like to test POST.

The node server is running and I am using postman to check if the endpoint is working.

I am unclear on how to format the post data and my POST requests result in errors when I send them.

My API is below:

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;

My Schema is as follows:

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;

In Postman, my URL is "http://localhost:5000/api/todos" and I am adding a body with the key as "action" and the value as "asdf". On send I get the following result:

{
    "error": "The input field is empty"
}

Could you please let me know how to format my body data so that I can test my POST endpoint properly?

GoBlueDev
  • 73
  • 3

1 Answers1

1
  1. Open Postman, select request as POST and click on Body.

  2. Under Body, select raw and insert your data in the space below like this and change from text to JSON option:-

    { "action":"asdf" }

  3. Please make sure to add this to your app.js file before any route handler

    const app = express(); app.use(express.json());

Jatin Mehrotra
  • 9,286
  • 4
  • 28
  • 67
  • Sure, I just tried that. Unfortunately I get the same response back. { "error": "The input field is empty" } – GoBlueDev Aug 17 '20 at 02:51
  • 1
    I am sorry I missed one thing, when you select raw make sure to change the option from text to JSON (you can see this beside GraphQl option) I have updated the answer, hope it helps. – Jatin Mehrotra Aug 17 '20 at 04:18
  • The best way to test an external resource like an endpoint would be to mock it. For the same, you can first format your data using a middleware - as @JatinMehrotra mentions using express.json() Testing an endpoint that used MongoDB - you can opt to use the MongoDB in-memory server – Hrishikesh D Kakkad Nov 21 '20 at 04:52