1

I'm desperately trying to send data via POST to a express.js application. The express.js app works fine but for whatever reason the POST data isn't sent to the server properly:

var xhrConfig = {
  url: "http://localhost:3000/test",
  body: {"foo": "bar"},
  // body: JSON.stringify({"foo": "bar"}),
  // body: 'foo=bar',
  method: "POST"
};
document.createElement('core-xhr').request(xhrConfig);

My express.js console.log(req.body) output is always {}. No matter if body is sent stringified or raw or JSON. I also tried params instead of body just to make sure.

I tried the same in jQuery to exclude the possibility of having a bug in my express.js route but $.ajax({url: 'http://localhost:3000/test', data: {foo: 'bar'}, type: 'POST'}); works perfectly fine.

So what's the reason that req,body is always empty? Any ideas?

//edit:

body: "foo=bar",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},

This one works now but is there a way to be able to use body: {"foo": "bar"} instead of converting it to foo=bar first?

1

Looks like express looks at the Content-Type header to determine what type of body it has, below works for me.

this.$.xhr.request({
    url: "/my/url", 
    method: "POST",
    headers:{
        "Content-Type":"application/json"
    },
    body: JSON.stringify(survey), 
    callback: function(response){
        console.log(response);
    }
});
|improve this answer|||||
0

I had this problem as well on Polymer. This problem is very frustrating because there isn't much documentation on Polymer on core-xhr.

As you have already answered the first question yourself, I'll answer the latter: yes/no. If you look at the source of <core-xhr>, it just feeds the params straight to xhr.send(params). however, there is a method inside of called toQueryString, which does what you want to do.

toQueryString: function(params) {
    var r = [];
    for (var n in params) {
      var v = params[n];
      n = encodeURIComponent(n);
      r.push(v == null ? n : (n + '=' + encodeURIComponent(v)));
    }
    return r.join('&');
  }
|improve this answer|||||
1

As far as I know, core-xhr is a low level element, and the body object on it's conf doesn't accept a JS object but the string body you want to use.

For the use you describe, you could try core-ajax, a higher level element that can be configured with an object. Doc on core-ajax: https://www.polymer-project.org/docs/elements/core-elements.html#core-ajax.

<core-ajax
  auto
  url="http://localhost:3000/test"
  body='{"foo": "bar"}'
  handleAs="json"
  method: "POST"
  on-core-response="{{handleResponse}}"></core-ajax>

Hope it helps. If you need a more detailed example, don't hesitate to ask.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.