【问题标题】:Meteorjs handle scraped data from server to client returns undefinedMeteorjs 处理从服务器到客户端的抓取数据返回未定义
【发布时间】:2020-05-28 19:59:39
【问题描述】:

我正在尝试为我的 Meteor + React 应用程序实现 url 预览,当用户在 textarea 中粘贴 url 时,他们将获得 url 的预览。我计划通过使用几个 npm 模块来实现这一点,即:

  1. url-regex,和
  2. open-graph-scraper

我了解为避免出现任何 CORS 问题,请求应在服务器端完成。 所以我目前已经设置好了:

//在客户端

import urlRegex from 'url-regex';
const onTextareaChange = e => {
    let value = e.target.value;
    let testURL = urlRegex().test(value) //returns true if url exists in textarea
    console.log(testURL);
    if(testURL){
        let extractURL = value.match(urlRegex()) //extract the url
        extractURL.map(url =>{
            console.log(url)
            Meteor.call('scrapeURL',{url}, function (result){
                 console.log(result)         
            })

        })
    }
    /* console.log(e.target.value) */
    setTextarea(e.target.value)
 }

//在服务器上

import ogs from 'open-graph-scraper';
/* 24. scrapeURL */
'scrapeURL' ({url}){
  new SimpleSchema({
    url : { type  : String }
  }).validate({url})
  if(!Meteor.userId){
    throw new Meteor.Error('not-authorised!')
  } else {
    let options = { 'url': url };
      ogs(options)
        .then(function (result) {
          console.log('result:', result);
          return result;
        })
        .catch(function (error) {
          console.log('error:', error);
        });
  }
}    

这里的问题是,当我尝试在服务器上console.log results 时,抓取的数据显示在服务器控制台中。但是当我尝试将results 从服务器返回到客户端时,客户端上的console.log 显示undefined

我不知道代码有什么问题。

【问题讨论】:

    标签: javascript reactjs web-scraping meteor


    【解决方案1】:

    您的 scrapeUrl 函数不返回任何数据(您只描述了 .then() 函数将返回的内容),您应该尝试这种方式:

    import ogs from 'open-graph-scraper';
    /* 24. scrapeURL */
    'scrapeURL' ({url}){
      new SimpleSchema({
        url : { type  : String }
      }).validate({url})
      if(!Meteor.userId){
        throw new Meteor.Error('not-authorised!')
      } else {
        let options = { 'url': url };
    
        // here return the full promise : 
        return ogs(options)
            .then(function (result) {
              console.log('result:', result);
              return result;
            })
            .catch(function (error) {
              console.log('error:', error);
              // probably here a need to tell the client that there was an error
              //throw new Meteor.Error(error);
            });
      }
    }   
    

    这是关于在 Meteor 中使用 Promise 的好读物: https://blog.meteor.com/using-promises-and-async-await-in-meteor-8f6f4a04f998

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-16
      • 1970-01-01
      • 1970-01-01
      • 2014-03-25
      • 1970-01-01
      • 2015-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多