服务器端 API 中未定义 Svelte/Sapper fetch/this.fetch

Ell*_*ung 1 api svelte sapper

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

  • 我有一个文件在/src/routes/login.js
  • 根据 Sapper 文档,它将在 中创建一个 API 端点http://<my_domain>/login,它会这样做
  • 现在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,我可以继续fetch在服务器端API请求中使用吗?

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

非常感谢。

Jax*_*axx 5

安装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
Run Code Online (Sandbox Code Playgroud)

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

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

但这在您的用例中可能是多余的,因为服务器路由根据定义是在服务器端执行的。