简体   繁体   English

iron-ajax绑定并将JSON写入文件

[英]iron-ajax bind and write JSON to file

I have the following iron-ajax element in my html: 我的html中包含以下iron-ajax元素:

<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: 我在上面的html的js文件中有这个:

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: 此时, tweets是一个JSON对象数组:

在此处输入图片说明

Now I'm trying to send this back to the node.js server so I can write/save it to a file. 现在,我尝试将其发送回node.js服务器,以便可以将其写入/保存到文件中。

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

I have the following in app.js: 我在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. 在这里我req.body了错误,我不知道如何访问我发送的JSON, req.body似乎为空。 Same happens if I try to wrap tweets in a getter (eg doing {returnTweets(){ return this.tweets;}, and body='[{"statuses": "{{returnTweets()}}"}]' . 如果我尝试{returnTweets(){ return this.tweets;}, tweets包装在吸气剂中(例如,执行{returnTweets(){ return this.tweets;}, and body='[{"statuses": "{{returnTweets()}}"}]'

Can anyone advise on how I could pass the JSON and print it? 谁能建议我如何传递JSON并进行打印?

UPDATE 更新

OK so I'm managing to bind the tweets to the body of the request by doing 好的,因此我正在通过以下方式将推文绑定到请求body

<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. 其中tweetsParsed是包含JSON.stringify ed tweets的属性。 Now if I check the ajax request, it contains the tweets in the body: 现在,如果我检查了ajax请求,它在主体中包含推文:

在此处输入图片说明

HOWEVER, I'm still not getting anything on the server side, and console. 但是,我仍然无法在服务器端和控制台上得到任何东西。 logging request.body returns {} ... Any idea why this is happening? 正在记录request.body返回{} ...知道为什么会这样吗?

  1. Can you confirm that json was send to server (via chrome dev tools)? 您可以确认json是否已通过chrome dev工具发送到服务器?
  2. Dont use iron-ajax its buggy as hell try fetch which is nativly supported by your browser 不要使用Iron-ajax的越野车作为地狱尝试获取 ,这是浏览器天生支持的
  3. If you actually send your json to the backend it should be in request.body.statuses 如果您实际上将json发送到后端,则应在request.body.statuses

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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