为什么 SveltKit 中的操作会给出“错误:无法使用操作预渲染页面”?

Ziu*_*lpa 4 javascript vite sveltekit

我有一个 SvelteKit 应用程序,只需遵循文档https://learn.svelte.dev/tutorial/named-form-actions中的示例,问题是一切正常,直到我尝试编写一个操作:

在: +page.server.js

export const actions = {
    default: async () => {
        console.log('test')
    }
};
Run Code Online (Sandbox Code Playgroud)

vite 立即失败并显示:“无法使用操作预渲染页面”

Error: Cannot prerender pages with actions
    at render_page (file:///mydir/node_modules/@sveltejs/kit/src/runtime/server/page/index.js:87:11)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async resolve (file:///mydir/node_modules/@sveltejs/kit/src/runtime/server/index.js:356:17)
    at async respond (file:///mydir/node_modules/@sveltejs/kit/src/runtime/server/index.js:229:20)
    at async file:///mydir/node_modules/@sveltejs/kit/src/exports/vite/dev/index.js:444:22
Run Code Online (Sandbox Code Playgroud)

可能我缺少一些配置或忘记了一些基础知识,知道吗?

H.B*_*.B. 6

该文档简单地指出:

Pages with actions cannot be prerendered, because a server must be able to handle the action POST requests.

The assumption is probably that a form action should have an effect on the page when submitted, which would not be possible when a static HTML page is served every time.

You could try to separate any logic to an API endpoint that is not associated with your prerendered page. It depends on what you are trying to do here, maybe the page should simply not be prerendered at all.

This means that +page.ts should set:

export const prerender = false;
Run Code Online (Sandbox Code Playgroud)