I have a svelte application and would like to make an API call to my server from JavaScript. The key is that I want to use a relative url i.e., instead of:
fetch("https://example.com/foo);
I want to do:
fetch("/foo");
but if I try to do that I get this error:
Error: Cannot use relative URL (/$) with global fetch — use `event.fetch` instead: https://kit.svelte.dev/docs/web-standards#fetch-apis at globalThis.fetch (file:///Users/xxx/code/xxx-svelte-app/node_modules/@sveltejs/kit/src/exports/vite/dev/index.js:35:10)
This issue is documented here. Its a long thread but as far as I could understand the solution offered is to use the load method. However, this does not work for me as the API call needs to be made dynamically (AJAX).
I tried prefixing all my urls with window.location.origin
e.g.:
fetch(window.location.origin +"/foo")
but now the code does not build:
ReferenceError [Error]: window is not defined
I don't understand why would Svelte compiler give this error. Granted window
does not exist in Node.js but it exists in the browser. And Svelte code is supposed to run in the browser!
I also read this post btw but again the solution offered does not help me.
What is the way out here? There ought to be one. Setting the base url using environment variable is not a solution for me as it creates a lot of hassle - the app may be running on localhost, in dev, test, prod etc.