SvelteKit生产环境获取静态JSON文件报500错误求助
解决SvelteKit生产环境(Convox + adapter-node)读取静态JSON文件超时问题
问题原因
在Server端load函数中使用相对路径fetch('/schemas/${schema}.json')时,本地开发环境下SvelteKit Dev Server会自动代理请求到静态资源目录,但生产环境使用@sveltejs/adapter-node打包后,Node.js进程中的fetch会尝试通过网络请求自身服务的静态资源。由于Convox容器的网络配置限制,这种内部HTTP请求可能出现连接超时,导致500错误。
解决方案
直接通过Node.js文件系统读取静态JSON文件,避免通过网络请求获取,既解决超时问题,也提升性能。
修改后的[schema]/+page.server.js代码
import fs from 'node:fs/promises'; import path from 'node:path'; export async function load({ params }) { const { schema } = params; // 构建静态JSON文件的绝对路径 const filePath = path.join( process.cwd(), 'build', 'static', 'schemas', `${schema}.json` ); try { // 读取文件内容并解析为JSON const fileContent = await fs.readFile(filePath, 'utf8'); const json = JSON.parse(fileContent); return { json }; } catch (err) { // 文件不存在时返回404错误 if (err.code === 'ENOENT') { throw new Error('Schema not found', { status: 404 }); } // 其他错误向上抛出 throw err; } }
注意事项
- 确保
static/schemas目录下的所有JSON文件在build过程中被正确复制到build/static/schemas,SvelteKit默认会自动处理静态资源的复制。 - 验证Convox容器中Node.js进程拥有读取
build/static/schemas目录的权限,通常默认配置即可满足需求。
内容的提问来源于stack exchange,提问作者Ringziii
相关产品推荐
相关产品推荐

