sveltejs / sapper

The next small thing in web development, powered by Svelte
https://sapper.svelte.dev
MIT License
7k stars 434 forks source link

500 when fetching content when navigating #1253

Closed gavinmcfarland closed 4 years ago

gavinmcfarland commented 4 years ago

I've created a small utility for publishing content to an API which can be used for static sites. I've added it to Sapper but I've encountered an issue. When you navigate between pages a 500 error is given and it fails to fetch the content. If you visit the link directly it's fine and the content is displayed.

Here is an example of where the route fetches content (I've used examples from the real-world Sapper app.)

https://github.com/limitlessloop/stancy/blob/master/examples/sapper/src/routes/about.svelte

And here is the API used to get the data.

https://github.com/limitlessloop/stancy/blob/master/examples/sapper/src/node_modules/api.js

It appears that when using export async function preload() it's only successful when visiting the URL directly. I can test this by just using console.log().

<script context="module">
  import * as api from "api.js";
  export async function preload({ params }) {
    console.log("content successfully loaded");
    const { slug } = params;
    const page = await api.get(`pages/about`, null);
    return { page, slug };
  }
</script>

Interestingly I can remove the async keyword and it works (even though it is technically invalid).

Conduitry commented 4 years ago

This is a CORS problem. The server running at localhost:4000 isn't configured so that browsers will allow requests from other origins. It works during SSR because the server-side Fetch library doesn't follow CORS restrictions.

gavinmcfarland commented 4 years ago

Thanks @Conduitry . I've not had to deal with CORS and not that familiar with it, so I hadn't considered this. But knowing this I was able to set the header to allow Access-Control-Allow-Origin from any origin. Thanks again!