Jeffrey Van Dalsum
Jeffrey Van Dalsum

Reputation: 85

Angular $http POST escaping nested objects

So, I am 100% certain I am missing something obvious here but I've tried everything I can think of. I'm attempting to setup a simple $http POST request in angular:

$http({
      url: 'http://api.local.com/sign_in.json',
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      params: test5
    })

I'm attempting to send in an object that has a key of 'user' and a value of another object which has two key value pairs (email and password) as can be seen below:

var temp2 = {
  'user': {
    'email': '[email protected]',
    'password': 'testing'
  }
};

var test5 = {'user':{'email':'[email protected]','password':'testing'}};

However, when I posted any of the versions I've tried (which are far more than what's shown above), I receive a response from the server of:

Started POST "/sign_in.json?user=%7B%22email%22:%[email protected]%22,%22password%22:%22testing%22%7D" for 127.0.0.1 at 2015-03-02 16:22:58 -0500
Processing by V1::SessionsController#create as JSON
Parameters: {"user"=>"{\"email\":\"[email protected]\",\"password\":\"testing\"}"}

The first level 'user' key comes in correct, however the entire nested object that's the value of the 'user' key are escaped.

If I change the var test5 = { 'user' : 'test' }, the parameters come in correctly so the issue is the nested object. I need the parameters to come in as:

Parameters: {"user"=>{"email":"[email protected]","password":"testing"}}

not:

Parameters: {"user"=>"{\"email\":\"[email protected]\",\"password\":\"testing\"}"}

Been a bit of a long day so apologies if I am missing something super obvious here. Thanks for the help in advance.

Upvotes: 1

Views: 2049

Answers (1)

Jasen
Jasen

Reputation: 14250

By using params your test5 is url encoded and appears in the URL. Since you are sending user info you probably want to use data instead of params.

$http({
    url: 'http://api.local.com/sign_in.json',
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    data: test5
})

Also note that single quotes is not valid JSON.

Upvotes: 1

Related Questions