Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Sending and Receiving Data with Route Handlers | Section
Building Web Apps with Next.js

bookSending and Receiving Data with Route Handlers

Swipe um das Menü anzuzeigen

Now that you understand how Route Handlers work, let's connect them with your frontend.

In real applications, users submit data through forms, and your app needs to send that data to the server and process it.

In Next.js, this is done by sending a request from a Client Component to a Route Handler.

Example - Sending Data from a Form

"use client";

import { useState } from "react";

export default function ContactForm() {
  const [name, setName] = useState("");

  async function handleSubmit(e) {
    e.preventDefault();

    await fetch("/api/contact", {
      method: "POST",
      body: JSON.stringify({ name }),
      headers: {
        "Content-Type": "application/json",
      },
    });
  }

  return (
    <form onSubmit={handleSubmit}>
      <input
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      <button type="submit">Submit</button>
    </form>
  );
}

This form sends data to the server when submitted.

Receiving Data in a Route Handler

export async function POST(request: Request) {
  const data = await request.json();

  return Response.json({
    message: "Received",
    data,
  });
}

This handler receives the data and returns a response.

How It Works

When the form is submitted:

  1. The browser sends a POST request to /api/contact;
  2. The Route Handler processes the request;
  3. The server returns a response;
  4. The client can use this response if needed.

Using the Response

You can also handle the response in your component:

const res = await fetch("/api/contact", {
  method: "POST",
  body: JSON.stringify({ name }),
  headers: {
    "Content-Type": "application/json",
  },
});

const result = await res.json();
console.log(result);
question mark

How do you send data from a Client Component to a Route Handler in Next.js?

Wählen Sie die richtige Antwort aus

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 1. Kapitel 28

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 1. Kapitel 28
some-alt