简体   繁体   中英

Angular2. HTTP.POST doesn't work

this is my HTTP service right here :

    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.

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...

How do I send the body correctly?

PS : I tested this with POSTMAN and it works!

Looks like the issue is in building the post params, try

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.

If this doesn't work, check with Google Developer tool on what your request is sending to the server.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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