diff --git a/src/content/docs/ja/recipes/build-forms-api.mdx b/src/content/docs/ja/recipes/build-forms-api.mdx new file mode 100644 index 0000000000000..6b598dd14518f --- /dev/null +++ b/src/content/docs/ja/recipes/build-forms-api.mdx @@ -0,0 +1,478 @@ +--- +title: APIルートでフォームを構築する +description: JavaScriptを使ってフォーム送信をAPIルートへ送る方法を学びます。 +i18nReady: true +type: recipe +--- +import { Steps } from '@astrojs/starlight/components'; +import UIFrameworkTabs from "~/components/tabs/UIFrameworkTabs.astro"; +import PackageManagerTabs from "~/components/tabs/PackageManagerTabs.astro"; + +HTMLフォームはページを再読み込みしたり、別ページへ遷移したりします。代わりにAPIエンドポイントへフォームデータを送信するには、JavaScriptでフォーム送信をインターセプトする必要があります。 + +このレシピでは、フォームデータをAPIエンドポイントへ送信し、そのデータを処理する方法を説明します。 + +## 前提条件 +- [オンデマンドレンダリング用のアダプター](/ja/guides/on-demand-rendering/)を導入したプロジェクト +- [UIフレームワークのインテグレーション](/ja/guides/framework-components/)をインストールしていること + +## レシピ + + +1. フォームデータを受け取る`POST`のAPIエンドポイント`/api/feedback`を作成します。`request.formData()`で処理します。使用前に必ず値を検証します。 + + + この例ではメッセージを含むJSONオブジェクトをクライアントへ返します。 + + ```ts title="src/pages/api/feedback.ts" "request.formData()" "post" + export const prerender = false; // Not needed in 'server' mode + import type { APIRoute } from "astro"; + + export const POST: APIRoute = async ({ request }) => { + const data = await request.formData(); + const name = data.get("name"); + const email = data.get("email"); + const message = data.get("message"); + // Validate the data - you'll probably want to do more than this + if (!name || !email || !message) { + return new Response( + JSON.stringify({ + message: "Missing required fields", + }), + { status: 400 } + ); + } + // Do something with the data, then return a success response + return new Response( + JSON.stringify({ + message: "Success!" + }), + { status: 200 } + ); + }; + ``` + +2. 使用中のUIフレームワークでフォームコンポーネントを作成します。各入力には、その値の意味を表す`name`属性を付けます。 + + + 必ず送信用の`