简体   繁体   中英

Can't do POST requests with Polymer's core-ajax

This is what I have:

 Polymer('my-element', { created: function() { this.data = { name: 'John Doe', email: 'john@doe.com' }; }, handleResponse: function(e, d) { console.log(d.response); } }); 
 <core-ajax id="ajax" auto url="/test" method="POST" handleAs="json" body="{{data}}" on-core-response="{{handleResponse"}}> </core-ajax> 

And I have a server set up to return the body of the POST message when the user posts to /test.

app.post('/test', function(req, res) {
    res.json(req.body);
}

However, this is what I get as response on the console:

Object {object Object: ""}

This looks like core-ajax performs the AJAX call before this.data in ready.

Try 'manuel' AJAX request initiation, ie ajax.go() Do this inside:

 created: function() {
    this.data = {
       name: 'John Doe',
       email: 'john@doe.com'
     }; 
    var respuesta = this.$.ajax;
    console.log(respuesta);
    respuesta.go();
},

Example Plunk

core ajax all data you want to get with post must be sent with params attribute not body attribute.

that would make your core ajax tag look like

<core-ajax
       id="ajax"
       auto
       url="/test"
       method="POST"
       handleAs="json"
       params="{{data}}"
       on-core-response="{{handleResponse"}}>
</core-ajax>

that would allow you to catch the data like normal in node

app.post('/test', function(req, res) {
  res.json(req.body);
}

it is confusing cause in node you think of params as get data and body as post data but this doesn't matter with core ajax. all data get or post is sent with the params attribute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM