ultimate_beaver
ultimate_beaver

Reputation: 85

Angular 2 http post is sent as empty object or on the key side

I'm trying to send data from angular 2 to node js on the server side my angular code is

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

  }

and on the server side

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

when I console.log it on the server side I get an empty object {} when I use contentType: application/json and when I use contentType: application/x-www-form-urlencoded I get all the data on the key side of the object eg. {'{type:house}':''} I tried using JSON.stringify on the data on the client side but no help

N.B. I'm using cors dependency on the server side

Upvotes: 3

Views: 1046

Answers (2)

Dom
Dom

Reputation: 638

Since I cannot comment on Mahmoud Youssef's last comment, I'm writing this one:

Since you're dealing with JSON objects, and would like to convert them into a form url encoded, would be best to do the following:

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

Then simply post body.toString() as a value when sending back to the server, make sure that the json or class object are matching what the server accepts

it's very important to import URLSearchParams from @angular/http in angular2 as URLSearchParams won't be defined in Microsoft Edge/IE, see URLSearchParams Browser's compatibility

Upvotes: 0

ultimate_beaver
ultimate_beaver

Reputation: 85

I found the answer, I used content-Type: application/x-www-form-urlencoded

and used:

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

urlSearchParams can be imported from http library in angular 2

Upvotes: 1

Related Questions