【问题标题】:Svelte/Sapper fetch/this.fetch is not defined in Server side APISvelte/Sapper fetch/this.fetch 未在服务器端 API 中定义
【发布时间】:2021-05-21 09:16:27
【问题描述】:

这是我关于使用 Svelte/Sapper 的问题

  • 我在/src/routes/login.js 中有一个文件
  • 根据 Sapper 文档,它将在 http://<my_domain>/login 中创建一个 API 端点,它会这样做
  • 现在在login.js,我想调用另一个API服务器,假设它是http://another_server/auth
  • 无论我如何使用fetch 函数:fetch("http://another_server/auth")this.fetch("http://another_server/auth"),Svelte 响应:(this.)fetch is not defined
  • 文档说应该在preload()内运行,所以我把fetch包在export async function preload(){}下,没用

所以我的问题是:除了使用axios,我可以在服务器端API请求中继续使用fetch吗?

刚刚在模板[slug].json.js文件中测试,当我添加(this.)fetch函数时,它没有编译,同样的错误:(this.)fetch is not defined

非常感谢。

【问题讨论】:

    标签: api svelte sapper


    【解决方案1】:

    安装node-fetch npm 包并在您的服务器路由中使用它,而不是默认的fetch

    (在 /src/routes/login.js 中):

    import fetch from 'node-fetch'
    ...
    // inside your route handler
    const response = await fetch('http://another_server/auth') // no error
    

    如果您不确定代码是在客户端还是服务器端执行(即您正在寻找通用/同构方法),您可以使用条件 require:

    // inside your route handler
    const fetch = process.browser ? window.fetch : require('node-fetch').default
    const response = await fetch('http://another_server/auth') // no error
    

    但这在您的用例中可能有点矫枉过正,因为根据定义,服务器路由是在服务器端执行的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-22
      • 2020-10-23
      • 2020-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-18
      • 2021-12-11
      相关资源
      最近更新 更多