我应该如何格式化POST数据以测试Express API端点? [英] How should I format my POST data for testing an express API endpoint?
问题描述
我正在关注: https://www.digitalocean.com/community/tutorials/getting-started-with-mern-stack .
我想测试使用express构建的API端点.我想测试POST.
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.
我不清楚如何格式化帖子数据,发送后的POST请求会导致错误.
I am unclear on how to format the post data and my POST requests result in errors when I send them.
我的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;
在邮递员中,我的网址是"http://localhost:5000/api/todos"并且我要添加一个主体,其键为"action"(动作)值是"asdf".发送后,我得到以下结果:
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"
}
能否让我知道如何格式化我的身体数据,以便我可以正确地测试POST端点?
Could you please let me know how to format my body data so that I can test my POST endpoint properly?
推荐答案
-
打开邮递员,选择请求"为POST,然后单击正文".
Open Postman, select request as POST and click on Body.
在正文"下,选择原始",然后将数据插入下面的空白处,然后从文本更改为JSON选项:-
Under Body, select raw and insert your data in the space below like this and change from text to JSON option:-
{"action":"asdf";}
{ "action":"asdf" }
请确保在任何路由处理程序之前将其添加到您的app.js文件中
Please make sure to add this to your app.js file before any route handler
const app = express();app.use(express.json());
const app = express(); app.use(express.json());
这篇关于我应该如何格式化POST数据以测试Express API端点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!