Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

POST body not sending through cURL using JSON

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

enter image description here

>Solution :

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());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading