首页 > 解决方案 > 我应该如何格式化我的 POST 数据以测试快速 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', (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;

我的架构如下:

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;

在 Postman 中,我的 URL 是“http://localhost:5000/api/todos”,我正在添加一个正文,其中键为“action”,值为“asdf”。在发送时,我得到以下结果:

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

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

标签: javascriptexpresspostmanschemaendpoint

解决方案


  1. 打开 Postman,选择请求作为 POST,然后单击正文。

  2. 在 Body 下,选择 raw 并像这样在下面的空间中插入您的数据,然后从 text 更改为 JSON 选项:-

    {“动作”:“asdf”}

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

    常量应用程序 = 快递();app.use(express.json());


推荐阅读