0Pricing
Next.js 15 Fullstack Web Apps · 课时

使用服务器操作构建全栈表单

使用服务器操作直接在服务器上处理表单提交,简化数据变更。

使用服务器操作构建全栈表单 是 CoddyKit 上的免费 Next.js 15 Fullstack Web Apps 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Next.js 15 Fullstack Web Apps 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Next.js 15 Fullstack Web Apps 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

What are Server Actions?

Server Actions in Next.js 15 allow you to run server-side code directly from your React components. They are a powerful feature that simplifies data mutations and backend interactions.

Think of them as tiny, direct connections to your server logic, without needing to create separate API routes for every backend task.

Forms and Server Actions

One of the primary uses for Server Actions is handling form submissions. When you link an HTML <form> element to a Server Action, the browser automatically sends the form data to your server-side function.

  • The action attribute of the <form> points directly to your Server Action function.
  • This eliminates the need for client-side JavaScript to capture and send form data, making forms simpler and more robust.

Defining Your First Action

A Server Action is simply an asynchronous JavaScript function marked with the "use server" directive. This directive tells Next.js that the function should be executed on the server.

You can define Server Actions directly within your React components (if they are Server Components) or in separate files for better organization.

Basic Server Action Example

Let's create a simple form that takes a username. When submitted, a Server Action will log the username on the server. Notice the "use server" at the top of the function.

// app/page.js

// This async function is our Server Action
async function processUsername(formData) {
  "use server"; // Marks this function to run on the server
  const username = formData.get('username'); // Get value by input's 'name' attribute
  console.log('Server received username:', username);
  // In a real application, you'd typically save this to a database
}

export default function HomePage() {
  return (
    <div>
      <h1>Enter Your Username</h1>
      <form action={processUsername}> {/* Link form to the Server Action */}
        <input type="text" name="username" placeholder="Your username" required />
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

Accessing Form Data

When a form is submitted to a Server Action, the action receives a FormData object as its first argument. This object is a standard web API that contains all the key-value pairs from your form's input fields.

  • Use formData.get('fieldName') to retrieve the value of a specific input.
  • The 'fieldName' must match the name attribute of your HTML input element (e.g., <input name="username" />).

Redirecting After Submission

After a user successfully submits a form and your Server Action processes the data (e.g., saves it to a database), you often want to redirect them to another page, such as a confirmation or a list view.

Next.js provides a redirect function from next/navigation that you can call directly within your Server Action to navigate the user to a new route.

Action with Redirect Example

Let's enhance our form to redirect the user after a successful submission. Here, we'll redirect to a /success-page.

// app/page.js
import { redirect } from 'next/navigation'; // Import the redirect function

async function handleSubmit(formData) {
  "use server";
  const username = formData.get('username');
  console.log('Processing username:', username);

  // In a real app, you'd do database operations here

  // After successful processing, redirect the user
  redirect('/success-page'); 
}

export default function SignupPage() {
  return (
    <div>
      <h1>Sign Up</h1>
      <form action={handleSubmit}>
        <input type="text" name="username" placeholder="Username" required />
        <button type="submit">Register</button>
      </form>
    </div>
  );
}

// Note: For this example to fully work, you would need an actual
// app/success-page/page.js file with some content.

Basic Error Handling

Server Actions can encounter errors, such as invalid input or database issues. You can use standard JavaScript try...catch blocks within your action to gracefully handle these potential problems.

For more advanced error feedback to the user, you might return data from the action to the client component or use a specialized form library.

Updating UI with Revalidation

After a Server Action successfully mutates data (e.g., adding a new post), your user interface might need to update to reflect this change. Next.js provides functions like revalidatePath or revalidateTag from next/cache.

These functions tell Next.js to re-fetch and re-render data for a specific path or a cached data tag, ensuring your users always see the latest information without a full page refresh.

Server Action Question

Consider the following Server Action and form in a Next.js App Router application:

// app/add-task/page.js
import { redirect } from 'next/navigation';

async function createTask(formData) {
  "use server";
  const taskTitle = formData.get('title');

  if (taskTitle.length < 5) {
    throw new Error('Task title must be at least 5 characters long.');
  }

  console.log('Creating task:', taskTitle);
  // Simulate saving to database
  redirect('/tasks');
}

export default function AddTaskPage() {
  return (
    <form action={createTask}>
      <input type="text" name="title" placeholder="Task Title" />
      <button type="submit">Add Task</button>
    </form>
  );
}

Recap: Fullstack Forms

You've mastered how Server Actions simplify fullstack form handling in Next.js 15!

  • Server Actions (`"use server"`) execute code directly on the server.
  • HTML <form action={yourAction}> automatically sends FormData to your action.
  • Access form fields using formData.get('name').
  • Use redirect from next/navigation for post-submission navigation.
  • Implement error handling with try...catch within your actions.
  • Consider revalidatePath or revalidateTag to update UI after data mutations.

This pattern reduces boilerplate and streamlines your data mutation workflows.

常见问题解答

「使用服务器操作构建全栈表单」课时是免费的吗?

是的 — 「使用服务器操作构建全栈表单」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Next.js 15 Fullstack Web Apps 课程的其余内容,请升级到 CoddyKit PRO。 Next.js 15 Fullstack Web Apps 课程共包含 4 节课。

「使用服务器操作构建全栈表单」这节课中我会学到什么?

使用服务器操作直接在服务器上处理表单提交,简化数据变更。 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack Web Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Next.js 15 Fullstack Web Apps 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Next.js 15 Fullstack Web Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「使用服务器操作构建全栈表单」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Next.js 15 Fullstack Web Apps 课中编写并运行代码吗?

能。每节 Next.js 15 Fullstack Web Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 受控组件与状态
  2. 使用 React Hook Form 进行表单验证
  3. 使用服务器操作构建全栈表单
  4. 文件上传与多部分表单处理
← 返回 Next.js 15 Fullstack Web Apps