SvelteKit基于数据库Slug导航,部署GitHub Pages遇404错误
问题原因
GitHub Pages是静态文件托管服务,不支持Node.js后端运行,而你当前代码用了SvelteKit的PageServerLoad服务端加载函数,部署后这些服务端代码无法执行;同时静态站点默认不会将子路由请求 fallback 到入口文件,导致直接访问子路由或刷新页面时出现404。
解决步骤
1. 切换到静态适配模式
先安装SvelteKit的静态适配器:
npm install @sveltejs/adapter-static
修改svelte.config.js,替换原有适配器配置:
import adapter from '@sveltejs/adapter-static'; import { vitePreprocess } from '@sveltejs/vite-plugin-svelte'; /** @type {import('@sveltejs/kit').Config} */ const config = { preprocess: vitePreprocess(), kit: { adapter: adapter({ fallback: 'index.html' // 让所有路由请求都指向入口文件,由客户端路由处理 }), paths: { base: '/你的仓库名称/' // 若部署在「用户名.github.io/仓库名」路径下,必须配置此项 } } }; export default config;
2. 替换服务端加载为客户端数据获取
因为GitHub Pages不支持服务端代码执行,需要把PageServerLoad的逻辑移到客户端:
删除原页面的PageServerLoad代码,在组件中用客户端方式实现数据获取:
<script> import { onMount } from 'svelte'; import { supabase } from '$lib/supabaseClient'; import { page } from '$app/stores'; import { goto } from '$app/navigation'; import { base } from '$app/paths'; let topicInput = ''; let help = ''; let topicData = null; let error = null; // 搜索逻辑保留,注意使用$base获取配置的基础路径 async function searchDatabase() { if (topicInput.trim() === '') { help = '表单不能为空,请输入水果名称(提示:输入"Apple")'; return; } const { data, error: fetchError } = await supabase .from('Topics') .select('Description') .eq('Topic', topicInput); if (fetchError) { help = `获取数据失败:${fetchError.message}`; } else if (data.length === 0) { help = '未找到该水果,请重试'; } else { goto(`${$base}/${topicInput}`); } } // 页面加载时从客户端请求数据 onMount(async () => { const slug = $page.params.slug; try { const { data, error: fetchError } = await supabase .from('Topics') .select('Topic, Description') .eq('Topic', slug) .single(); if (fetchError || !data) { error = '未找到内容'; return; } topicData = data; } catch (err) { error = '服务器内部错误'; } }); </script> <!-- 搜索表单区域 --> <input bind:value={topicInput} placeholder="输入水果名称" /> <button on:click={searchDatabase}>搜索</button> {#if help} <p>{help}</p> {/if} <!-- 内容展示区域 --> {#if error} <p>{error}</p> {:else if topicData} <h1>{topicData.Topic}</h1> <p>{topicData.Description}</p> {/if}
3. 配置GitHub Pages部署
- 执行
npm run build生成dist文件夹 - 将
dist文件夹内的所有文件推送到GitHub仓库的gh-pages分支 - 在GitHub仓库的「Settings-Pages」页面,将部署源设置为
gh-pages分支的/root路径
关键注意点
base路径必须配置正确,否则路由跳转和资源加载会出错- 所有数据获取逻辑必须放在客户端(比如
onMount、组件内异步函数),不能使用服务端加载函数 - 适配器的
fallback: 'index.html'是解决子路由404的核心,确保GitHub Pages将所有路由请求转发到入口文件,由SvelteKit客户端路由处理
内容的提问来源于stack exchange,提问作者Cameron Johnson
相关产品推荐
相关产品推荐

