这是我关于使用 Svelte/Sapper 的问题
/src/routes/login.jshttp://<my_domain>/login,它会这样做login.js,我想调用另一个API服务器,假设它是http://another_server/authfetch功能: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
非常感谢。
安装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)
但这在您的用例中可能是多余的,因为服务器路由根据定义是在服务器端执行的。
| 归档时间: |
|
| 查看次数: |
933 次 |
| 最近记录: |