简体   繁体   中英

iron-ajax bind and write JSON to file

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:

在此处输入图片说明

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 (eg 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.stringify ed tweets. Now if I check the ajax request, it contains the tweets in the body:

在此处输入图片说明

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

  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

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