问题
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:
Open Postman, select request as POST and click on Body.
Under Body, select raw and insert your data in the space below like this and change from text to JSON option:-
{ "action":"asdf" }
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