简体   繁体   English

角度2。 HTTP.POST不起作用

[英]Angular2. HTTP.POST doesn't work

this is my HTTP service right here : 这是我的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);
    })
}

It seems that it doesn't send the body to the POST request. 似乎它不会将正文发送到POST请求。

these output the correct value of the body 这些输出正确的身体价值

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

But

console.log(res.text());

It gives me a DB validation Error, which states that the body and country are required... 它给了我一个DB验证错误,该错误指出必须输入正文国家/地区 ...

How do I send the body correctly? 如何正确发送尸体?

PS : I tested this with POSTMAN and it works! PS:我用POSTMAN测试了它,它可以工作!

Looks like the issue is in building the post params, try 看起来问题出在建立post params中,尝试

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

Note that my hash keys are not strings, because stringify will convert a JavaScript object to a JSON string. 请注意,我的哈希键不是字符串,因为stringify会将JavaScript对象转换为JSON字符串。

If this doesn't work, check with Google Developer tool on what your request is sending to the server. 如果这不起作用,请使用Google Developer工具检查您向服务器发送的请求。

I have added 我已经添加了

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM