代码之家  ›  专栏  ›  技术社区  ›  Gnome-Improvement713

POST正文未使用JSON通过cURL发送

  •  -1
  • Gnome-Improvement713  · 技术社区  · 2 年前

    我正在尝试使用邮递员向我的应用程序发送邮件。发送POST消息时,我收到一个HTTP 200代码。在响应中,我只得到递增的id,而不是我发送的JSON对象。

    我正在为我的应用程序使用Node和Express

    这是我的申请和发帖方法

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

    enter image description here

    帖子标题 enter image description here

    enter image description here

    2 回复  |  直到 2 年前
        1
  •  0
  •   Phil    2 年前

    你的主要问题是你的路线不接受 route parameters 但你正试图使用 req.params.name

    您的数据位于 req.body

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

    要使用curl发送等效的请求,请使用以下命令

    curl \
      -H "content-type: application/json" \
      -d '{"name":"abcde"}' \
      "http://localhost:3000/api/courses"
    

    express.json() 中间件没有 extended 选项

    app.use(express.json());
    
        2
  •  0
  •   jignesh.world    2 年前

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