我想在服务器端进行fetch操作并在前端显示出来。但在加载数据之前它不会打开页面。我希望它在页面打开后加载数据。我为 seo 执行了 feth 过程,访问者看不到我在哪里执行了 fetch 过程。
fetch.js
export async function fetchData(page) {
try {
const response = await fetch('https://fetch);
const data = await response.json();
return data;
} catch (error) {
console.error('Hata oluştu:', error);
}
}
+page.server.js
import { fetchData } from '$lib/fetch';
export async function load() {
let sliderData;
let jsonData = [];
let filteredData = [];
const jsonDataPromise = fetchData('images');
const sliderDataPromise = fetchData('slider');
await Promise.all([jsonDataPromise, sliderDataPromise]);
filteredData = jsonData.filter(item => item.category === '');
sliderData = sliderDataPromise.data;
return {
filteredData: filteredData,
sliderData: sliderData,
}
}
页面.svelte
<script>
import Slider from '$lib/Slider.svelte';
import welcome from '$lib/images/svelte-welcome.webp';
import welcome_fallback from '$lib/images/svelte-welcome.png';
import Images from '$lib/imageView.svelte';
export let data;
</script>
<svelte:head>
<title>Home</title>
<meta name="description" content="Svelte demo app" />
</svelte:head>
<section>
<h1>
<span class="welcome">
<picture>
<source srcset={welcome} type="image/webp" />
<img src={welcome_fallback} alt="Welcome" />
</picture>
</span>
</h1>
{#if data}
<Slider data={data.sliderData} />
{:else}
<p>Loading...</p>
{/if}
</section>
{#if data}
<div class="image-container">
{#if data.filteredData}
{#each data.filteredData as image, i}
<Images {image} />
{/each}
{/if}
</div>
{:else}
<p>Loading...</p>
{/if}
您可以流数据(阅读本文),这通过将承诺作为子属性返回来工作。您不能在加载函数中等待承诺,否则等待会在页面返回之前发生。
因此,如果您想过滤数据,则必须将其链接起来以兑现承诺。比如:
const dataPromise = fetchData(...).then(data => data.filter(...));
return {
streamed: {
data: dataPromise,
}
};