【问题标题】:Consuming external API using SvelteKit works but only after reloading route使用 SvelteKit 使用外部 API 有效,但仅在重新加载路由之后
【发布时间】:2021-07-25 18:46:25
【问题描述】:

使用 SvelteKit 1.0.0-next.95 从外部 API 端点获取 JSON 数组并在模板中显示,如下所示:

<script context="module">
  export async function load({ fetch }) {
    const url = 'https://www.schoolhouseyoga.com/api/announcement'
    const res = await fetch(url, {
      method: 'GET',
      mode: 'cors',
      headers: {
        'content-type': 'application/json'
      }
    })

    if (res.ok) {
      return {
        props: {
          sections: await res.json()
        }
      }
    }

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

<script>
  export let sections = []
</script>

<template>
  <section>
    {#if sections.length > 0}
      <div class="callout">
        <h1>Announcements</h1>
        {#each sections as section}
          <div>
            {#if section.announcements.length > 0}
              <h2>{section.section}</h2>
            {/if}
            {#each section.announcements as announcement}
              <p><b>{announcement.title} </b>- {@html announcement.description}</p>
            {/each}
          </div>
        {/each}
      </div>
    {/if}
  </section>
</template>

如果您在浏览器中尝试https://www.schoolhouseyoga.com/api/announcement (CORS) 或使用 curl,您将获得一个包含两个元素的 JSON 数组。

当我在开发模式下运行 npm run dev -- --open 并在 Safari 14.1 (macOS) 上导航到此路由时,我收到 500 错误和消息,“访问不允许访问源 http://localhost:3000-控制-允许-来源。”如果我尝试在 Google Chrome 上导航到该路线,我会收到 500 错误和“TypeError: Failed to fetch”。

但是对于任一浏览器,如果我刷新页面,数据就会成功加载。导航到不同的路线然后再次返回,错误再次出现。

我猜这与 SSR 有关,但不知道该怎么办。

有什么想法吗?

【问题讨论】:

    标签: fetch endpoint svelte-3 sveltekit


    【解决方案1】:

    问题与服务器端渲染和端点的 CORS 问题有关。当服务器端代码执行获取时,它工作正常。客户端正在执行后续提取(遇到了 CORS 问题)。

    虽然端点似乎启用了 CORS...

    import { Router } from 'express';
    import cors from 'cors';
    import * as controller from './announcement.controller';
    
    const router = Router();
    
    router.get('/', cors(), controller.index);
    

    但是端点也在使用头盔并且需要

    app.use(helmet.permittedCrossDomainPolicies());
    

    在加载路线之前。

    希望这对其他人有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-26
      • 2013-06-23
      • 2020-05-08
      • 2019-01-15
      • 2013-07-12
      • 1970-01-01
      • 2022-10-16
      • 2012-05-08
      相关资源
      最近更新 更多