我应该如何格式化POST数据以测试Express API端点?

问题描述

我正在关注:https://www.digitalocean.com/community/tutorials/getting-started-with-the-mern-stack

我想测试使用express构建的API端点。我想测试POST。

节点服务器正在运行,我正在使用邮递员检查端点是否正常工作。

我不清楚如何格式化帖子数据,发送后的POST请求会导致错误

我的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',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',next) => {
  Todo.findOneAndDelete({"_id": req.params.id})
    .then(data => res.json(data))
    .catch(next)
})

module.exports = router;

我的架构如下:

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;

在邮递员中,我的URL是“ http:// localhost:5000 / api / todos”,我要添加一个主体,其键为“ action”,值为“ asdf”。发送后,我得到以下结果:

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

能否让我知道如何格式化我的身体数据,以便我可以正确地测试POST端点?

解决方法

  1. 打开邮递员,选择“请求”为POST,然后单击“正文”。

  2. 在“正文”下,选择“原始”,然后将数据插入下面的空白处,然后从文本更改为JSON选项:-

    { “ action”:“ asdf” }

  3. 请确保在任何路由处理程序之前将其添加到您的app.js文件中

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