Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1541

How to make an API call in Svelte using a relative url?

$
0
0

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.


Viewing all articles
Browse latest Browse all 1541

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>