Reputation: 1126
I am trying to build a simple app with Svelte to learn.
in my FastAPI backend (main.py) I simply have an endpoint hello:
@app.get("/hello")
async def hello():
return "Hello"
I have the middlewares set up like this so requests from svelte should be allowed:
origins = [
"http://localhost:5173",
"localhost:5173"
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"]
)
In the svelte app I have:
function getHello()
{
fetch("hello").then(d => d.text);
}
console.log("the hello message", getHello());
but I get:
the hello message undefined
I have tried this with a similar template I have from reacts useQuery which seems to work. I am thinking I might be setting up the folders wrong.
FastAPI is in /backend
and the svelte app is in /my-app/src just from the basic tutorial installation.
Any pointers and tips on things to try and get this set up is greatly appreciated
Upvotes: 0
Views: 2991
Reputation: 184607
The code you use to fetch the data cannot work like this.
log
) does not account for it being asynchronous(Also, the path 'hello'
is relative, so this will only work with the correct site path in the browser.)
If the path is correct and the server works, the code should look more like this:
function getHello() {
return fetch("hello").then(d => d.text);
}
getHello().then(text => console.log("the hello message", text));
Alternative async
functions could be used or Svelte's {#await}
directive.
(async () => {
console.log("the hello message", await getHello()));
})();
{#await getHello() then text}
{text}
{/await}
Upvotes: 2