Build Forms With API Routes
このコンテンツはまだ日本語訳がありません。
An HTML form causes the browser to refresh the page or navigate to a new one. To send form data to an API endpoint instead, you must intercept the form submission using JavaScript.
This recipe shows you how to send form data to an API endpoint and handle that data.
Prerequisites
- A project with SSR (
output: 'server'
) enabled - A UI Framework integration installed
Recipe
-
Create a form component using your UI framework. Each input should have a
name
attribute that describes the value of that input.Be sure to include a
<button>
or<input type="submit">
element to submit the form. -
Create the
POST
API endpoint that will receive the form data. Userequest.formData()
to process it. Be sure to validate the form values before you use them.This example sends a JSON object with a message back to the client.
-
Create a function that accepts a submit event, then pass it as a
submit
event handler to your form. In the function, callpreventDefault
on the event to override the browser’s default submission process.Then, create a
FormData
object and send it to your endpoint usingfetch
.