【问题标题】:Angular2. HTTP.POST doesn't work角2。 HTTP.POST 不起作用
【发布时间】:2016-05-21 12:37:00
【问题描述】:

这是我的 HTTP 服务:

    postData(name, country) {
  var body = JSON.stringify({
    "name":name,
    "country":country
  });
  console.log(name);     // it outpus the correct value
  console.log(country);  // it outpus the correct value
  return this.http.post('http://178.62.58.150:5000/api/cosmo/',body)
    .map(res => {
      res.text();
      console.log(res.text());

    })
    .do(data => {
      this.data = data;
      // console.log(this.data);
    })
}

似乎它没有将正文发送到 POST 请求。

这些输出正确的body值

console.log(name);     
console.log(country); 

但是

console.log(res.text());

它给了我一个数据库验证错误,它指出 bodycountry 是必需的...

如何正确发送正文?

附: : 我用 POSTMAN 测试过,效果很好!

【问题讨论】:

    标签: node.js http angular ionic2 angular2-services


    【解决方案1】:

    看起来问题在于构建帖子参数,尝试

    var body = JSON.stringify({
      name: name,
      country: country
    })
    

    请注意,我的哈希键不是字符串,因为stringify 会将 JavaScript 对象转换为 JSON 字符串。

    如果这不起作用,请使用 Google Developer tool 检查您的请求发送到服务器的内容。

    【讨论】:

    • 这不是问题
    【解决方案2】:

    我已经添加了

    let headers = new Headers();
     headers.append("Content-Type","application/json");
    
    return this.http.post('http://178.62.58.150:5000/api/cosmo/',body,{headers:headers})
    

    【讨论】:

    • 使用 RequestOptions。新的 RequestOptions({headers: headers});不要忘记导入它们
    猜你喜欢
    • 2017-04-13
    • 2015-04-25
    • 2014-05-26
    • 1970-01-01
    • 2016-08-09
    • 2019-01-12
    • 2017-07-08
    • 1970-01-01
    • 2017-02-28
    相关资源
    最近更新 更多