跳转到内容
搜索文档

Static Forms

最后更新 查看 MarkdownAgent 设置

Static Forms Pages Plugin 拦截所有设置了 data-static-form-name 属性的表单提交。这样你可以对表单提交采取行动,例如将提交保存到 KV。

安装

npm i @cloudflare/pages-plugin-static-forms

用法

import 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 值)。它应返回 ResponsePromise<Response>。在此 respondWith 函数中,你可以采取行动,例如序列化 formData 并保存到 KV namespace。

HTML 表单的 methodaction 属性无需设置。Plugin 将自动覆盖它们以拦截提交。

这篇文档对您有帮助吗?