コンテンツにスキップ

静的フォーム

静的フォームページプラグインは、data-static-form-name属性が設定されたすべてのフォーム送信を intercept します。これにより、例えば、送信内容を KV に保存するなど、これらのフォーム送信に対してアクションを実行できます。

インストール

Terminal window
npm install @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(
`こんにちは、${email}さん! ${name} フォームの送信ありがとうございます。`,
);
},
});
<body>
<h1>販売問い合わせ</h1>
<form data-static-form-name="sales">
<label>メールアドレス <input type="email" name="email" /></label>
<label>メッセージ <textarea name="message"></textarea></label>
<button type="submit">送信</button>
</form>
</body>

プラグインは、respondWithプロパティを持つオブジェクトという単一の引数を取ります。この関数は、formDataプロパティ(FormDataインスタンス)とnameプロパティ(data-static-form-name属性の名前値)を持つオブジェクトを受け取ります。ResponseまたはResponsePromiseを返す必要があります。このrespondWith関数内で、formDataをシリアライズしてKV名前空間に保存するなどのアクションを実行できます。

HTMLフォームのmethodおよびaction属性は設定する必要はありません。プラグインは、送信を intercept できるように自動的にそれらを上書きします。