Static Forms Pages Plugin 拦截所有设置了 data-static-form-name 属性的表单提交。这样你可以对表单提交采取行动,例如将提交保存到 KV。
npm i @cloudflare/pages-plugin-static-formsyarn add @cloudflare/pages-plugin-static-formspnpm add @cloudflare/pages-plugin-static-formsbun add @cloudflare/pages-plugin-static-formsimport staticFormsPlugin from "@cloudflare/pages-plugin-static-forms";
export const onRequest: PagesFunction = staticFormsPlugin({
respondWith: ({ formData, name }) => {
const email = formData.get("email");
return new Response(
`Hello, ${email}! Thank you for submitting the ${name} form.`,
);
},
});<body>
<h1>Sales enquiry</h1>
<form data-static-form-name="sales">
<label>Email address <input type="email" name="email" /></label>
<label>Message <textarea name="message"></textarea></label>
<button type="submit">Submit</button>
</form>
</body>Plugin 接受单个参数(一个对象),包含 respondWith 属性。此函数接受一个对象,包含 formData 属性(FormData ↗ 实例)和 name 属性(data-static-form-name 属性的 name 值)。它应返回 Response 或 Promise<Response>。在此 respondWith 函数中,你可以采取行动,例如序列化 formData 并保存到 KV namespace。
HTML 表单的 method 和 action 属性无需设置。Plugin 将自动覆盖它们以拦截提交。