How should I format my POST data for testing an express API endpoint?

安稳与你 提交于 2021-01-29 18:20:43

问题


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?


回答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());



来源:https://stackoverflow.com/questions/63443303/how-should-i-format-my-post-data-for-testing-an-express-api-endpoint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!