带有 sapper 的雅虎财务模块

yahooFinance module with sapper

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

基本上我正在尝试的是从 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: "Africa/Abidjan|LMT GMT|g.8 0|01|-2ldXH.Q|48e5",

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

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

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

创建文件 yahoo.json.js 并将其放入 src/routes。然后将以下内容复制+粘贴到其中。这将从 yahoo-finance 和 return 调用 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)}

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