最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot fetch data from localhost using Sveltekit - Stack Overflow

programmeradmin1浏览0评论

In a new Sveltetkit project, I'm trying to fetch rest API from my local backed:

<script context="module">
    export async function load() {
        const url = `http://127.0.0.1:9000/v1/articles`;
        const res = await fetch(url, {
            method: "GET",
            headers: {
                "Access-Control-Allow-Origin": "*"
            }
            });

        if (res.ok) {
            let articles = await res.json()
            console.log('res is:', articles);
            return {
                props: {
                    articles: articles
                }
            };
        }

        return {
            status: res.status,
            error: new Error(`Could not load ${url}`)
        };
    }
</script>
  
  <script>
    export let articles;
    
  </script>

 
<h2>List of articles</h2>

{#each articles as dastan}
  <h4>{dastan.title}</h4>
{/each}}

I can see the json response being printed in the server's terminal However I get this error in browser:

500
Failed to fetch
TypeError: Failed to fetch
    at load (http://127.0.0.1:3000/src/routes/articles/index.svelte:188:20)
    at Renderer._load_node (http://127.0.0.1:3000/.svelte-kit/dev/runtime/internal/start.js:953:37)
    at Renderer.start (http://127.0.0.1:3000/.svelte-kit/dev/runtime/internal/start.js:536:29)
    at async start (http://127.0.0.1:3000/.svelte-kit/dev/runtime/internal/start.js:1207:15)

And this error in the chrome's console

Access to fetch at 'http://127.0.0.1:9000/v1/articles' from origin 'http://127.0.0.1:3000' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

Despite allowing all origins in the backend server (in go gin) and adding "Access-Control-Allow-Origin": "*" to request above I could not remove this CORS problem. So I have no clue what else could be wrong.

In a new Sveltetkit project, I'm trying to fetch rest API from my local backed:

<script context="module">
    export async function load() {
        const url = `http://127.0.0.1:9000/v1/articles`;
        const res = await fetch(url, {
            method: "GET",
            headers: {
                "Access-Control-Allow-Origin": "*"
            }
            });

        if (res.ok) {
            let articles = await res.json()
            console.log('res is:', articles);
            return {
                props: {
                    articles: articles
                }
            };
        }

        return {
            status: res.status,
            error: new Error(`Could not load ${url}`)
        };
    }
</script>
  
  <script>
    export let articles;
    
  </script>

 
<h2>List of articles</h2>

{#each articles as dastan}
  <h4>{dastan.title}</h4>
{/each}}

I can see the json response being printed in the server's terminal However I get this error in browser:

500
Failed to fetch
TypeError: Failed to fetch
    at load (http://127.0.0.1:3000/src/routes/articles/index.svelte:188:20)
    at Renderer._load_node (http://127.0.0.1:3000/.svelte-kit/dev/runtime/internal/start.js:953:37)
    at Renderer.start (http://127.0.0.1:3000/.svelte-kit/dev/runtime/internal/start.js:536:29)
    at async start (http://127.0.0.1:3000/.svelte-kit/dev/runtime/internal/start.js:1207:15)

And this error in the chrome's console

Access to fetch at 'http://127.0.0.1:9000/v1/articles' from origin 'http://127.0.0.1:3000' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

Despite allowing all origins in the backend server (in go gin) and adding "Access-Control-Allow-Origin": "*" to request above I could not remove this CORS problem. So I have no clue what else could be wrong.

Share Improve this question edited Nov 15, 2021 at 7:17 blnks asked Nov 15, 2021 at 7:02 blnksblnks 1,1612 gold badges10 silver badges21 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 1

That's because you have to setup the backend to use CORS midlleware. In an express BE the mand would be app.use(cors()) after you install the package named cors. https://www.npmjs./package/cors

Or use something similar for the environment you're working on.

OK, I found the solution. Actually I should not have put "Access-Control-Allow-Origin": "*" in the request header. CORS is taken care of, if server is peroperly configured to allow the origin. In my case I just had to user cors middleware in gin:

r.Use(cors.Default()) 

Here is the working solution if sveltekit:

 <script context="module">
  export async function load({ fetch }) {
    const res = await fetch('http://127.0.0.1:9000/v1/articles');
    const articles = await res.json() ;
  if (res.ok) return { props: { articles: articles } };
  return {
    status: res.status,
    error: new Error()
   };
  }
</script>
  
  <script>
    export let articles = [];    
  </script>

 
<h2>Articles</h2>
 
{#each articles as article}
   <h4>{article.title}</h4>
{/each}
Note to self
  1. When fetching, make sure to prefix the URL with http:// e.g. await fetch('http://localhost:3000') unless you need to set HTTPS for localhost.
  2. Unless you allow CORS for all domains/origins, make sure to include the port in CORS configuration if the origin uses a port since it is considered to be of the same origin if and only if the protocol, host and port are exactly the same.
发布评论

评论列表(0)

  1. 暂无评论