3

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

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.