(Angular4 / MEAN) 向本地发送请求 API 结果为空

(Angular4 / MEAN) Sending Request to Local API Results in Empty Body

我正在尝试 post 数据到项目 API,例如:

"data": {
        "title": "stack",
        "notes": "asdsad",
        "time": "19:02",
        "meridian": "PM",
        "type": "Education",
        "_id": "5a2f02d3bba3640337bc92c9",
        "days": {
            "Monday": true,
            "Tuesday": false,
            "Wednesday": false,
            "Thursday": false,
            "Friday": false,
            "Saturday": false,
            "Sunday": false
        }
    }

但是,当使用 HttpClient 来 post 数据时

  this.http.post("http://localhost:3000/api/items",
      JSON.stringify(item))
      .subscribe(
        (val) => {
          console.log("POST call successful value returned in body",
            val);
        },
        response => {
          console.log("POST call in error", response);
        },
        () => {
          console.log("The POST observable is now completed.");
        });

我总是从 API 中的 Items Controller 收到 Bad Request 400 响应。

exports.createItem = async function(req, res, next){

    // Req.Body contains the form submit values.
    console.log(req);
    console.log(req.body);
    var item = {
        id: req.body.id,
        title: req.body.title,
        days: req.body.days,
        notes: req.body.notes,
        time: req.body.time,
        meridian: req.body.meridian,
        type: req.body.type,
        completed: req.body.completed,
    }

    try{

        // Calling the Service function with the new object from the Request Body

        var createdItem = await ItemService.createItem(item)
        return res.status(201).json({status: 201, data: createdItem, message: "Succesfully Created Item"})
    } catch(e){
        console.log(e);
        //Return an Error Response Message with Code and the Error Message.
        return res.status(400).json({status: 400, message: "Item Creation was Unsuccesfull"})
    }
}

我已经在 app.js 中设置了 BodyParser

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

在express控制台中,输出如下

  _startTime: 2017-12-11T22:35:18.204Z,
  _remoteAddress: '::1',
  body: {},
  secret: undefined,
  cookies: {},
  signedCookies: {},
  route: 
   Route {
     path: '/',
     stack: [ [Object], [Object] ],
     methods: { post: true } } }
{}

如您所见,正文是空的,这会阻止创建项目。我已经使用 Postman 进行了测试,在发送 url 编码表单数据和原始 JSON 数据时,post 成功并且 return 200。但是,我永远无法让应用程序的请求工作。

感谢任何帮助,因为我已经为此苦苦挣扎了几个小时。

  this.http.post("http://localhost:3000/api/items",
      JSON.stringify(item)    -----> convert JSON object to string
   ).subscribe(...);

根据您的服务器端代码,我相信它需要 JSON 对象而不是 JSON 字符串,因此从您的客户端删除 JSON.stringify(item)),您的 POST 应该是 JSON 对象。