1

I have the following iron-ajax element in my html:

<iron-ajax
  id="write-tweets"
  body='[{"statuses": "{{tweets}}"}]'
  url="/fscall"
  handle-as="json">
</iron-ajax>

And I have this in the js file for the above html:

Polymer({
is: "sample-app",

properties: {
  tweets: {
    type: Object,
    value: [],
  },
},

handleResponse(e){
  console.log("_________Twitter responses aquired:_________");
  this.tweets = this.tweets.concat(e.detail.response.statuses);
  this.writeTweets();
},

At this point, tweets is an array of JSON objects:

enter image description here

Now I'm trying to send this back to the node.js server so I can write/save it to a file.

writeTweets(){
  let ajax = this.root.querySelector('#write-tweets');
  ajax.generateRequest();  
}
... //some unrelated code

I have the following in app.js:

app.get('/fscall', (req, res) => {  
  fs.writeFile("tweets.json", JSON.parse(req.body, null, 4), function(err) {
    if (err) {
      console.log(err);
    }
  });
});

And here I'm running into errors, I have no idea how to access the JSON that I sent, req.body seems to be empty. Same happens if I try to wrap tweets in a getter (e.g. doing {returnTweets(){ return this.tweets;}, and body='[{"statuses": "{{returnTweets()}}"}]'.

Can anyone advise on how I could pass the JSON and print it?

UPDATE

OK so I'm managing to bind the tweets to the body of the request by doing

<iron-ajax
  method="POST"
  id="write-tweets"
  body$='{"statuses": {{tweetsParsed}}}'
  url="/fscall"
  handle-as="json">
</iron-ajax>

Where tweetsParsed is a property that contains the JSON.stringifyed tweets. Now if I check the ajax request, it contains the tweets in the body:

enter image description here

HOWEVER, I'm still not getting anything on the server side, and console. logging request.body returns {}... Any idea why this is happening?

Community
  • 1
  • 1
lte__
  • 7,175
  • 25
  • 74
  • 131

1 Answers1

0
  1. Can you confirm that json was send to server (via chrome dev tools)?
  2. Dont use iron-ajax its buggy as hell try fetch which is nativly supported by your browser
  3. If you actually send your json to the backend it should be in request.body.statuses
Pascal L.
  • 1,261
  • 9
  • 21
  • I updated the question - I've managed to properly bind the tweets, but it's not being sent to the server. I'm pretty sure this should work with `iron-ajax` so I'd rather not add any external libraries. – lte__ Dec 06 '18 at 12:12
  • Mh honestly i´m still clueless. Maybe it is because from the client you send a post request but expect a get in your app.js? Can you see the body of the request containing the tweets in the dev tools of your browser? Can you post more code of your app.js file? – Pascal L. Dec 06 '18 at 17:33