Reputation: 1485
I am trying to post data using Polymer core-ajax component. After is call "go()" on below given component -
<core-ajax
id="createUserAjax"
url="/rest"
method="POST"
body='{"firstName":{{firstName}}, "lastName":{{lastName}}, "email":{{email}}}'
on-core-response="{{createUserResponse}}"></core-ajax>
Note that, its a post, and the body is a JSON. So naturally I would expect that the same JSON will be received on server side. But unfortunately on server I receive -
Body-------> {"{\"firstName\":foo, \"lastName\":bar, \"email\":fooatbar}":""}
Note that the JSON is broken at the end. Above log is printed from express log-
rest.post('/', function(req, res){
console.log("Body-------> "+JSON.stringify(req.body));
res.send(200);
});
I thought that it could be express or body-parser that is messing up. But on Chrome developer tool, under the "Form data" header it looks like this -
{"firstName":foo, "lastName":bar, "email":fooatbar}:
Note the trailing :. Because of this broken json, on server side i can't access the submitted json as dot notation.
Is this a bug? Or I am missing something?
Upvotes: 1
Views: 1038
Reputation: 176
You should probably use contentType="application/json" in order to treat the content as json. Otherwise, application/x-www-form-urlencoded is used and this makes the trailing ':'.
Hope this helps
Upvotes: 0
Reputation: 33
I had the same problème. I don't know why polymer makes that bad body. So i found that solution : To extract that
{\"firstName\":foo, \"lastName\":bar, \"email\":fooatbar}
From that
Body-------> {"{\"firstName\":foo, \"lastName\":bar, \"email\":fooatbar}":""}
I made that
var keys = Object.keys(req.body);
var strobj = keys[0];
var obj = JSON.parse(strobj);
Hope help. By
Upvotes: 0
Reputation: 8065
Change your body
attribute to this to make it valid JSON:
params='{"firstName":"{{firstName}}", "lastName":"{{lastName}}", "email":"{{email}}"}'
You forgot to wrap the values in quotation marks.
Upvotes: 1