【问题标题】:yahooFinance module with sapper带有工兵的雅虎财务模块
【发布时间】:2021-04-16 19:23:02
【问题描述】:

我正在做一个项目,我想使用来自 yahooFinance 的 darta。 我找到了这个项目https://www.npmjs.com/package/yahoo-finance。 我也使用了基本的工兵模板。

基本上我正在尝试从 YF 检索数据并将它们显示在 FE 上。

我给出了这段代码:

<script>
  import yahooFinance from 'yahoo-finance';
  let response;
  async function searchStock (){
    yahooFinance.historical({
      symbol: 'AAPL',
      from: '2020-01-01',
      to: '2020-12-31',
    }, function (err, quotes) {
      console.log(quotes)
    });
  }
</script>

但每次我尝试编译时,我都会得到: 意外令牌(请注意,您需要 @rollup/plugin-json 来导入 JSON 文件) 1:{ 2:“版本”:“2020d”, ^ 3:“区域”:[ 4:“非洲/阿比让|LMT GMT|g.8 0|01|-2ldXH.Q|48e5”,

所以我尝试以这种方式导入它var yahooFinance = require('yahoo-finance');

然后我得到 Uncaught (in promise) ReferenceError: require is not defined in the console.

【问题讨论】:

    标签: javascript node.js svelte sapper


    【解决方案1】:

    您将无法在前端使用 yahoo-finance 包,因为它使用 Node API。由于您使用的是 Sapper,因此您可以使用 server route 中的包并从客户端获取它。

    创建文件yahoo.json.js 并将其放入src/routes。然后将以下内容复制+粘贴到其中。这将从yahoo-finance 调用historical 方法并将结果作为JSON 返回。

    import yahooFinance from 'yahoo-finance';
    
    export async function get(req, res, next) {
      const response = await new Promise((resolve, reject) => {
        yahooFinance.historical({
          symbol: 'AAPL',
          from: '2020-01-01',
          to: '2020-12-31',
        }, function (err, quotes) {
          if (err) reject(err);
          resolve(quotes);
        });
      })
    
      res.setHeader('Content-Type', 'application/json');
      res.end(JSON.stringify(response));
    }
    

    然后,您可以从 Svelte 组件中调用此服务器路由。这使用 Sapper preload method 在页面呈现之前获取数据。

    <script context="module">
      export async function preload() {
        const res = await this.fetch('/yahoo.json');
        const data = await res.json();
    
        return {data};
      }
    
    </script>
    
    <script>
      export let data;
    </script>
    
    {JSON.stringify(data)}
    

    您可能希望增强服务器路由以添加请求参数和更好的错误处理,但这将向您展示如何使其工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-01
      • 1970-01-01
      • 2023-01-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多