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?

4

1 回答 1

0
  1. 您能否确认 json 已发送到服务器(通过 chrome 开发工具)?
  2. 不要使用 Iron-ajax 它的 bug 试试fetch,它是你的浏览器原生支持的
  3. 如果您实际上将 json 发送到后端,它应该在request.body.statuses
于 2018-12-06T10:17:31.030 回答