You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SvelteKit部署AWS Amplify遇500内部错误:预渲染配置异常

问题分析与解决方案

核心错误点

  1. 适配器未导入:svelte.config.js中使用了adapter但未导入@sveltejs/adapter-static,会导致构建失败,部署后非预渲染页面无法正常加载。
  2. POST函数未定义:/routes/login/+page.server.ts的actions里调用了POST('auth/login', ...),但没有导入或实现这个函数,运行时会抛出错误,服务器返回错误HTML而非预期JSON,前端解析时触发SyntaxError。
  3. 静态适配器与SSR冲突:adapter-static仅生成静态文件,无法处理需要服务器端逻辑(如+page.server.ts中的load、actions)的页面,AWS Amplify静态托管模式下也不会自动处理SSR请求。

修复步骤

1. 补全适配器导入

修改svelte.config.js,导入adapter-static:

import { vitePreprocess } from '@sveltejs/kit/vite';
import adapter from '@sveltejs/adapter-static'; // 新增适配器导入

/** @type {import('@sveltejs/kit').Config} */
const config = {
    preprocess: vitePreprocess(),

    kit: {
        adapter: adapter({
            fallback: 'index.html'
        }),
        prerender: {
            entries: ['*'] // 确保所有可预渲染页面被生成
        }
    }
};

export default config;

2. 修复POST函数调用

在/routes/login/+page.server.ts中,替换未定义的POST函数,根据API类型选择以下方式:

情况1:调用SvelteKit内部API路由

用event.fetch保持请求上下文:

// 修改actions中的请求逻辑
const res = await event.fetch('/auth/login', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({ email, p: password })
});

if (!res.ok) {
  return fail(400, { email, incorrect: true });
}

const resData = await res.json();

if (!resData.is_logged_in) {
  return fail(400, { email, incorrect: true });
}

情况2:调用外部后端API

封装原生fetch调用:

// 在文件顶部添加API调用封装
async function callApi(url: string, body: object) {
  const response = await fetch(`https://你的后端地址/${url}`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(body)
  });

  if (!response.ok) {
    throw new Error(`请求失败: ${response.status}`);
  }

  return response.json();
}

// 在actions中使用封装函数
const resData = await callApi('auth/login', { email, p: password });

3. 适配AWS Amplify部署

如果非预渲染页面依赖服务器端逻辑(如login的actions、load函数),adapter-static无法满足需求,需改用@sveltejs/adapter-amplify:

安装适配器

npm install @sveltejs/adapter-amplify

修改配置文件

import { vitePreprocess } from '@sveltejs/kit/vite';
import adapter from '@sveltejs/adapter-amplify';

/** @type {import('@sveltejs/kit').Config} */
const config = {
    preprocess: vitePreprocess(),

    kit: {
        adapter: adapter(),
        prerender: {
            entries: ['*']
        }
    }
};

export default config;

静态适配器兼容方案(可选)

若坚持使用adapter-static,需在Amplify控制台添加重写规则:

  • 进入应用的App settings > Rewrites and redirects
  • 添加规则:
    • 源地址:</^[^.]+$|\.(?!(css|gif|ico|jpg|js|png|txt|svg|woff|ttf|map|json)$)([^.]+$)/>
    • 目标地址:/index.html
    • 类型:200 (Rewrite)

内容的提问来源于stack exchange,提问作者PimVanLommel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 21:01:37