【问题标题】:Angular 2 http post is sent as empty object or on the key sideAngular 2 http post 作为空对象或在关键端发送
【发布时间】:2017-11-05 15:08:48
【问题描述】:

我正在尝试将数据从 angular 2 发送到服务器端的节点 js 我的角码是

addCrib(data:any) {
  let bodyString = data;
   let headers      = new Headers({ 'Content-Type': 'application/json' });
      return this.http.post('http://localhost:8000/addcribs',data , {headers:headers}).map(res => res.json()).subscribe(
        data => console.log(data)
      );

  }

在服务器端

addcribs: function(req,res){
    var x = req.body;
    console.log(x); // {} with application/json and { '{data....}':''} with application/x-www-form-urlencoded
    let crib = new Cribs({id:0, type:req.body.type,price:req.body.price,address:req.body.address,description:req.body.description,bedrooms:req.body.bedrooms,bathroom:req.body.bathroom,area: req.body.area,image:req.body.image});
    crib.save(function(err,crib){
      if(!err){
        res.json({success:true});
      }
    })
  }

当我在服务器端 console.log 时,我得到一个空对象 {},当我使用 contentType: application/json 时,当我使用 contentType: application/x-www-form-urlencoded 我得到所有数据对象的关键面,例如。 {'{type:house}':''} 我尝试在客户端的数据上使用 JSON.stringify 但没有帮助

注意我在服务器端使用 cors 依赖

【问题讨论】:

    标签: javascript node.js angular http post


    【解决方案1】:

    由于我无法对 Mahmoud Youssef 的最后一条评论发表评论,所以我正在写这个:

    由于您正在处理 JSON 对象,并且希望将它们转换为 url 编码的表单,因此最好执行以下操作:

    const body = new URLSearchParams();
    //The code below will take any JSON object into URLSearchParams variable, this way you won't need to keep assigning each value manually
    //value here refers to a typescript class or json object that you have
    Object.keys(value).forEach(key => {
      body.set(key, value[key]);
    });
    

    然后在发送回服务器时简单地将 body.toString() 作为值发布,确保 json 或 class 对象与服务器接受的匹配

    在 angular2 中从 @angular/http 导入 URLSearchParams 非常重要,因为 URLSearchParams 不会在 Microsoft Edge/IE 中定义,见URLSearchParams Browser's compatibility

    【讨论】:

      【解决方案2】:

      我找到了答案,我使用了 content-Type: application/x-www-form-urlencoded

      并使用:

      let urlSearchParams = new URLSearchParams();
      urlSearchParams.append('type', data.type);
      urlSearchParams.append('bathrooms', data.bathrooms);
      let body = urlSearchParams.toString()
      

      urlSearchParams 可以从 Angular 2 中的 http 库导入

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-23
        • 2019-06-09
        • 2018-08-30
        • 2017-09-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多