Here is my question about using Svelte/Sapper
/src/routes/login.js
http://<my_domain>/login
, which it doeslogin.js
, I would like to call another API server, assume that it is http://another_server/auth
fetch
function: fetch("http://another_server/auth")
, this.fetch("http://another_server/auth")
, Svelte responses: (this.)fetch is not defined
.preload()
, so I wrap the fetch under export async function preload(){}
, it did not workSo my question is: other than using axios
, can I keep on using fetch
in server side API request?
Just tested in the template [slug].json.js
file, when I add the (this.)fetch
function, it did not compile, same error: (this.)fetch is not defined
Thank you very much.
Install the node-fetch npm package and use that in your server routes instead of the default fetch
.
(in /src/routes/login.js):
import fetch from 'node-fetch'
...
// inside your route handler
const response = await fetch('http://another_server/auth') // no error
If you are unsure if the code will be executed on the client-side or the server-side (i.e. you're looking for a universal/isomorphic approach) you can use a conditional 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
But this is probably overkill in your use case since server routes are by definition executed on the server side.