javascript - 我应该如何格式化我的 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 端点?
解决方案
打开 Postman,选择请求作为 POST,然后单击正文。
在 Body 下,选择 raw 并像这样在下面的空间中插入您的数据,然后从 text 更改为 JSON 选项:-
{“动作”:“asdf”}
请确保在任何路由处理程序之前将此添加到您的 app.js 文件中
常量应用程序 = 快递();app.use(express.json());
推荐阅读
- go - go.mod 中的模块名称别名
- python - 在 Jupyter 的 Markdown 中加载纯文本内联
- dictionary - 如何在prefix_之后添加任何符号?
- google-cloud-firestore - Firestore 规则:在已定义规则的空集合上获得权限被拒绝
- css - SVG 中的阴影不是多重的,并且在不同的背景上颜色不同
- flutter - 如何获取 DocumentSnapshot 以按文档 ID 查询
- python - 从 find_all_palindromes 函数创建一个longest_palindrome 函数
- c++ - OpenCV:使用 PGM 文件。为什么我生成的 PGM 文件有 3 个通道 (RGB)?
- or-tools - Google ORTools - 不能共享相同路由的节点
- python - 如果我只传递一个参数,为什么会得到 TypeError?