node.js - (Angular4/MEAN) 向本地 API 发送请求会导致正文为空

标签 node.js angular express angular4-httpclient

我正在尝试将数据发布到 Items 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发布数据时

  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 中的项目 Controller 收到错误请求 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 数据时,帖子成功并返回 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 对象。

关于node.js - (Angular4/MEAN) 向本地 API 发送请求会导致正文为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47762751/

相关文章:

node.js - 将 GitHub 更新部署到 Azure 托管的 DocPad Node.js 网站会使网站脱机 1-2 分钟

node.js - 解析回调请求时出现多方错误

java - Angular 不通过 RESTful API 从 Spring 获取

node.js - Node/Angular 2 : Update navbar and show sidebar after user login

javascript - Express 4 和文件 session 存储

javascript - 创建路由 Express.js 和 MySql

node.js - A 与 B 无关

node.js - 使用 PhantomJS/Node.js 将 HTML 转换为可搜索的 PDF

angular - $q.all() 和 $q.race() 相当于 Angular 2 中的 Observables

javascript - 带或不带文件扩展名的 NodeJS 路由