简体   繁体   中英

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

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

Use this

   const course = {
      id: (courses.length + 1),
      name: req.body.name
   };

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM