I am trying to use Postman to send POST messages to my application. When sending the POST message, I receive an HTTP 200 code. In the response, I only get my incremented id, and not the JSON object I send.
When I try to use cURL from the CMD prompt, I get an error.
I am using Node and Express for my application
Here is my application and POST method
const express = require('express');
const Joi = require('joi');
const app = express();
app.use(express.json({extended: false}));
// POST
app.post('/api/courses', (req, res) => {
const {error} = validateCourse(req.body);
if(error){
return res.status(400).send(error.details[0].message);
}
const course = {
id: (courses.length 1),
name: req.params.name
};
courses.push(course);
res.send(course);
});
// validateCourse method
function validateCourse(course){
const schema = {
name: Joi.string().min(3).required()
};
return Joi.validate(course, schema);
}
Postman enter image description here
POST headers enter image description here
Application after several POST messages
CodePudding user response:
Your main problem is that your route accepts no route parameters but you are trying to use req.params.name
.
Your data is in req.body
const course = {
...req.body,
id: courses.length 1
};
To send the equivalent request with curl, use this
curl \
-H "content-type: application/json" \
-d '{"name":"abcde"}' \
"http://localhost:3000/api/courses"
FYI, the express.json() middleware doesn't have an extended
option
app.use(express.json());
CodePudding user response:
Use this
const course = {
id: (courses.length 1),
name: req.body.name
};