簡體   English   中英

如何為我的 Sveltekit 博客獲取並讀取正確的 JSON 文件?

[英]How do I fetch and read the correct JSON file for my Sveltekit blog?

我有 JSON 文件,其中包含我在src/data/posts/中的帖子的數據。 我正在嘗試為每個帖子創建頁面。 這是我的結構:

[projects]
|---[project].svelte
|---index.svelte

index.svelte包含列出我所有帖子的代碼。 [project].svelte中,我想渲染相關帖子的內容。 我試過這個:

<script context="module">
// All posts are contained in src/data/posts
// First, read the page.params.project and find the matching
// file name and read the data from that file.
export async function load({ page, fetch }) {
    const slug = page.params.project;
    let post;
    const url = `/src/data/posts/${slug}.json`
    post = await fetch(url)
    console.log(post)
}
</script>

但是,這並沒有得到我的 JSON 文件。 我得到以下回復:

500
Unexpected token < in JSON at position 0
SyntaxError: Unexpected token < in JSON at position 0

我控制台記錄了響應,它是這樣的:

[0] Response {
[0]   size: 0,
[0]   [Symbol(Body internals)]: {
[0]     body: <Buffer 3c 21 44 4f 43 54 59 50 45 20 68 74 6d 6c 3e 0a 3c 68 74 6d 6c 20 6c 61 6e 67 3d 22 65 6e 22 3e 0a 20 20 3c 68 65 61 64 3e 0a 20 20 20 20 0a 0a 09 09 ... 59964 more bytes>,
[0]     boundary: null,
[0]     disturbed: false,
[0]     error: null
[0]   },
[0]   [Symbol(Response internals)]: {
[0]     type: 'default',
[0]     url: undefined,
[0]     status: 404,
[0]     statusText: '',
[0]     headers: {
[0]       'content-type': 'text/html',
[0]       'permissions-policy': 'interest-cohort=()'
[0]     },
[0]     counter: undefined,
[0]     highWaterMark: undefined
[0]   }
[0] }

我不能這樣使用 fetch 嗎? 我該怎么做? 獲取我的帖子的正確方法是什么?

您需要將fetch response轉換為JSON

這可以使用.json()來完成

<script context="module">
// All posts are contained in src/data/posts
// First, read the page.params.project and find the matching
// file name and read the data from that file.
export async function load({ page, fetch }) {
    const slug = page.params.project;
    let post;
    const url = `/src/data/posts/${slug}.json`
    const resp = await fetch(url) /* added this line */
    post = await resp.json() /* added this line */
    console.log(post)
}
</script>

由於 fetch 僅適用於外部服務器,因此我使用動態導入來解決此問題。 相同的代碼現在寫成:

<script context="module">
    export async function load({ page }) {
        try {
            const Post = await import(`../../data/posts/${page.params.project}.json`);
            console.log(Post);
            return {
                // Data passed into svelte component
                props: {
                    Post:Post.default
                }
            };
        } catch (e) {
            return {
                props: {
                    Post: {
                        headling: "404",
                        content: "Page not found"
                    }
                }
            };
        }
    }
</script>

我可以像這樣提供Posts

<script>
export let Post;
</script>

這使我可以訪問 JSON 鍵值對(如Post.title )。

我試圖獲取的文件的路徑: src/routes/posts/index.json.ts

我以前有什么(這給了我一個錯誤):

500 Unexpected token < in JSON at position 0 SyntaxError: Unexpected token < in JSON at position 0

<script context="module" lang="ts">
  import type { Load } from "@sveltejs/kit";

  export const load: Load = async ({ fetch, url }) => {
    const res = await fetch("../routes/posts/index.json");
    return { props: { posts: await res.json() } };
  };
</script>

我之后(已修復):

<script context="module" lang="ts">
  import type { Load } from "@sveltejs/kit";

  export const load: Load = async ({ fetch, url }) => {
    const res = await fetch("/posts.json");
    return { props: { posts: await res.json() } };
  };
</script>

在閱讀了此處更新的 Sveltekit 文檔后,我最終解決了這個問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM