Formulare mit API-Routen erstellen
Formulare ermöglichen Ihnen das Erstellen und Aktualisieren von Daten in Webanwendungen. Next.js bietet eine leistungsstarke Möglichkeit, Datenmutationen mit API-Routen zu handhaben. Diese Anleitung zeigt Ihnen, wie Sie Formularübermittlungen auf dem Server verarbeiten.
Server-Formulare
Um Formularübermittlungen auf dem Server zu verarbeiten, erstellen Sie einen API-Endpunkt, um Daten sicher zu mutieren.
import type { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const data = req.body
const id = await createItem(data)
res.status(200).json({ id })
}
export default function handler(req, res) {
const data = req.body
// call your database, etc.
// const id = await createItem(data)
// ...
res.status(200).json({ data })
}
Rufen Sie dann die API-Route vom Client aus mit einem Event-Handler auf:
import { FormEvent } from 'react'
export default function Page() {
async function onSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault()
const formData = new FormData(event.currentTarget)
const response = await fetch('/api/submit', {
method: 'POST',
body: formData,
})
// Handle response if necessary
const data = await response.json()
// ...
}
return (
<form onSubmit={onSubmit}>
<input type="text" name="name" />
<button type="submit">Submit</button>
</form>
)
}
export default function Page() {
async function onSubmit(event) {
event.preventDefault()
const formData = new FormData(event.target)
const response = await fetch('/api/submit', {
method: 'POST',
body: formData,
})
// Handle response if necessary
const data = await response.json()
// ...
}
return (
<form onSubmit={onSubmit}>
<input type="text" name="name" />
<button type="submit">Submit</button>
</form>
)
}
Gut zu wissen:
- API-Routen legen keine CORS-Header fest, was bedeutet, dass sie standardmäßig nur same-origin sind.
- Da API-Routen auf dem Server ausgeführt werden, können wir sensible Werte (wie API-Schlüssel) über Umgebungsvariablen verwenden, ohne sie dem Client preiszugeben. Dies ist entscheidend für die Sicherheit Ihrer Anwendung.
Formularvalidierung
Wir empfehlen die Verwendung von HTML-Validierung wie required
und type="email"
für grundlegende clientseitige Formularvalidierung.
Für erweiterte serverseitige Validierung können Sie eine Schema-Validierungsbibliothek wie zod verwenden, um die Formularfelder vor der Datenmutation zu validieren:
import type { NextApiRequest, NextApiResponse } from 'next'
import { z } from 'zod'
const schema = z.object({
// ...
})
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const parsed = schema.parse(req.body)
// ...
}
import { z } from 'zod'
const schema = z.object({
// ...
})
export default async function handler(req, res) {
const parsed = schema.parse(req.body)
// ...
}
Fehlerbehandlung
Sie können React-State verwenden, um eine Fehlermeldung anzuzeigen, wenn eine Formularübermittlung fehlschlägt:
import React, { useState, FormEvent } from 'react'
export default function Page() {
const [isLoading, setIsLoading] = useState<boolean>(false)
const [error, setError] = useState<string | null>(null)
async function onSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault()
setIsLoading(true)
setError(null) // Vorherige Fehler löschen, wenn eine neue Anfrage startet
try {
const formData = new FormData(event.currentTarget)
const response = await fetch('/api/submit', {
method: 'POST',
body: formData,
})
if (!response.ok) {
throw new Error('Failed to submit the data. Please try again.')
}
// Handle response if necessary
const data = await response.json()
// ...
} catch (error) {
// Fehlermeldung erfassen, um sie dem Benutzer anzuzeigen
setError(error.message)
console.error(error)
} finally {
setIsLoading(false)
}
}
return (
<div>
{error && <div style={{ color: 'red' }}>{error}</div>}
<form onSubmit={onSubmit}>
<input type="text" name="name" />
<button type="submit" disabled={isLoading}>
{isLoading ? 'Loading...' : 'Submit'}
</button>
</form>
</div>
)
}
import React, { useState } from 'react'
export default function Page() {
const [isLoading, setIsLoading] = useState(false)
const [error, setError] = useState(null)
async function onSubmit(event) {
event.preventDefault()
setIsLoading(true)
setError(null) // Vorherige Fehler löschen, wenn eine neue Anfrage startet
try {
const formData = new FormData(event.currentTarget)
const response = await fetch('/api/submit', {
method: 'POST',
body: formData,
})
if (!response.ok) {
throw new Error('Failed to submit the data. Please try again.')
}
// Handle response if necessary
const data = await response.json()
// ...
} catch (error) {
// Fehlermeldung erfassen, um sie dem Benutzer anzuzeigen
setError(error.message)
console.error(error)
} finally {
setIsLoading(false)
}
}
return (
<div>
{error && <div style={{ color: 'red' }}>{error}</div>}
<form onSubmit={onSubmit}>
<input type="text" name="name" />
<button type="submit" disabled={isLoading}>
{isLoading ? 'Loading...' : 'Submit'}
</button>
</form>
</div>
)
}
Ladezustand anzeigen
Sie können React-State verwenden, um einen Ladezustand anzuzeigen, während ein Formular auf dem Server übermittelt wird:
import React, { useState, FormEvent } from 'react'
export default function Page() {
const [isLoading, setIsLoading] = useState<boolean>(false)
async function onSubmit(event: FormEvent<HTMLFormElement>) {
event.preventDefault()
setIsLoading(true) // Ladezustand auf true setzen, wenn die Anfrage startet
try {
const formData = new FormData(event.currentTarget)
const response = await fetch('/api/submit', {
method: 'POST',
body: formData,
})
// Handle response if necessary
const data = await response.json()
// ...
} catch (error) {
// Handle error if necessary
console.error(error)
} finally {
setIsLoading(false) // Ladezustand auf false setzen, wenn die Anfrage abgeschlossen ist
}
}
return (
<form onSubmit={onSubmit}>
<input type="text" name="name" />
<button type="submit" disabled={isLoading}>
{isLoading ? 'Loading...' : 'Submit'}
</button>
</form>
)
}
import React, { useState } from 'react'
export default function Page() {
const [isLoading, setIsLoading] = useState(false)
async function onSubmit(event) {
event.preventDefault()
setIsLoading(true) // Ladezustand auf true setzen, wenn die Anfrage startet
try {
const formData = new FormData(event.currentTarget)
const response = await fetch('/api/submit', {
method: 'POST',
body: formData,
})
// Handle response if necessary
const data = await response.json()
// ...
} catch (error) {
// Handle error if necessary
console.error(error)
} finally {
setIsLoading(false) // Ladezustand auf false setzen, wenn die Anfrage abgeschlossen ist
}
}
return (
<form onSubmit={onSubmit}>
<input type="text" name="name" />
<button type="submit" disabled={isLoading}>
{isLoading ? 'Loading...' : 'Submit'}
</button>
</form>
)
}
Weiterleitung
Wenn Sie den Benutzer nach einer Mutation zu einer anderen Route weiterleiten möchten, können Sie mit redirect
zu einer absoluten oder relativen URL umleiten:
import type { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const id = await addPost()
res.redirect(307, `/post/${id}`)
}
export default async function handler(req, res) {
const id = await addPost()
res.redirect(307, `/post/${id}`)
}