diff --git a/pages/docs/pages/building-your-application/data-fetching/forms-and-mutations.mdx b/pages/docs/pages/building-your-application/data-fetching/forms-and-mutations.mdx index c3c27b5..2f19a77 100644 --- a/pages/docs/pages/building-your-application/data-fetching/forms-and-mutations.mdx +++ b/pages/docs/pages/building-your-application/data-fetching/forms-and-mutations.mdx @@ -4,23 +4,21 @@ nav_title: Forms and Mutations description: Learn how to handle form submissions and data mutations with Next.js. --- -{/* TODO: 번역이 필요합니다. */} - # Forms and Mutations -Forms enable you to create and update data in web applications. Next.js provides a powerful way to handle form submissions and data mutations using **API Routes**. +폼은 웹 어플리케이션에서 데이터를 생성하고 업데이트할 수 있게 해줍니다. Next.js는 **API Routes**를 사용하여 폼 제출과 데이터 변형을 처리하는 강력한 방법을 제공합니다. -> **Good to know:** +> **알아두면 좋은 점:** > -> - We will soon recommend [incrementally adopting](/docs/app/building-your-application/upgrading/app-router-migration) the App Router and using [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) for handling form submissions and data mutations. Server Actions allow you to define asynchronous server functions that can be called directly from your components, without needing to manually create an API Route. -> - API Routes [do not specify CORS headers](https://developer.mozilla.org/docs/Web/HTTP/CORS), meaning they are same-origin only by default. -> - Since API Routes run on the server, we're able to use sensitive values (like API keys) through [Environment Variables](/docs/pages/building-your-application/configuring/environment-variables) without exposing them to the client. This is critical for the security of your application. +> - 곧 App Router를 [점진적으로 도입](/docs/app/building-your-application/upgrading/app-router-migration)하고 폼 제출 및 데이터 변형을 처리하기 위해 [Server Actions](/docs/app/building-your-application/data-fetching/server-actions-and-mutations) 사용을 권잘할 예정입니다. Server Actions를 사용하면 API Route를 수동으로 생성할 필요 없이 컴포넌트에서 직접 호출할 수 있는 비동기 서버 함수를 정의할 수 있습니다. +> - API Routes는 [CORS 헤더를 지정하지 않습니다](https://developer.mozilla.org/docs/Web/HTTP/CORS). 이는 기본적으로 동일 출처에서만 작동함을 의미합니다. +> - API Routes는 서버에서 실행되기 때문에 [환경 변수](/docs/pages/building-your-application/configuring/environment-variables)를 통해 API 키와 같은 민감한 값을 클라이언트에 노출하지 않고 사용할 수 있습니다. 이는 어플리케이션의 보안에 매우 중요합니다. ## Examples ### Server-only form -With the Pages Router, you need to manually create API endpoints to handle securely mutating data on the server. +Pages Router를 사용할 경우, 서버에서 데이터를 안전하게 변형하기 위해 API 엔드포인트를 수동으로 생성해야 합니다. ```ts filename="pages/api/submit.ts" switcher import type { NextApiRequest, NextApiResponse } from 'next' @@ -43,7 +41,7 @@ export default function handler(req, res) { } ``` -Then, call the API Route from the client with an event handler: +그 후, 이벤트 핸들러를 사용하여 클라이언트에서 API Route를 호출합니다: ```tsx filename="pages/index.tsx" switcher import { FormEvent } from 'react' @@ -58,7 +56,7 @@ export default function Page() { body: formData, }) - // Handle response if necessary + // 필요에 따라 응답 처리 const data = await response.json() // ... } @@ -83,7 +81,7 @@ export default function Page() { body: formData, }) - // Handle response if necessary + // 필요한 경우 응답 처리 const data = await response.json() // ... } @@ -99,9 +97,9 @@ export default function Page() { ## Form validation -We recommend using HTML validation like `required` and `type="email"` for basic client-side form validation. +기본적인 client-side 폼 검증을 위해 `required`와 `type="email"` 같은 HTML 검증을 사용하는 것을 권장합니다. -For more advanced server-side validation, you can use a schema validation library like [zod](https://zod.dev/) to validate the form fields before mutating the data: +더 정교한 server-side 검증을 위해 [zod](https://zod.dev/)와 같은 스키마 검증 라이브러리를 사용하여 데이터를 변형하기 전에 필드를 검증할 수 있습니다: ```ts filename="pages/api/submit.ts" switcher import type { NextApiRequest, NextApiResponse } from 'next' @@ -135,7 +133,7 @@ export default async function handler(req, res) { ### Error handling -You can use React state to show an error message when a form submission fails: +폼 제출이 실패했을 때 에러 메시지를 표시하기 위해 React state를 사용할 수 있습니다: ```tsx filename="pages/index.tsx" switcher import React, { useState, FormEvent } from 'react' @@ -147,7 +145,7 @@ export default function Page() { async function onSubmit(event: FormEvent) { event.preventDefault() setIsLoading(true) - setError(null) // Clear previous errors when a new request starts + setError(null) // 새 요청이 시작되면 이전 오류를 삭제 try { const formData = new FormData(event.currentTarget) @@ -160,11 +158,11 @@ export default function Page() { throw new Error('Failed to submit the data. Please try again.') } - // Handle response if necessary + // 필요한 경우 응답 처리 const data = await response.json() // ... } catch (error) { - // Capture the error message to display to the user + // 오류 메세지를 캡처하여 사용자에게 표시 setError(error.message) console.error(error) } finally { @@ -196,7 +194,7 @@ export default function Page() { async function onSubmit(event) { event.preventDefault() setIsLoading(true) - setError(null) // Clear previous errors when a new request starts + setError(null) // 새 요청이 시작되면 이전 오류를 삭제 try { const formData = new FormData(event.currentTarget) @@ -209,11 +207,11 @@ export default function Page() { throw new Error('Failed to submit the data. Please try again.') } - // Handle response if necessary + // 필요한 경우 응답 처리 const data = await response.json() // ... } catch (error) { - // Capture the error message to display to the user + // 오류 메세지를 캡처하여 사용자에게 표시 setError(error.message) console.error(error) } finally { @@ -237,7 +235,7 @@ export default function Page() { ## Displaying loading state -You can use React state to show a loading state when a form is submitting on the server: +서버에서 폼이 제출되는 동안 로딩 상태를 표시하기 위해 React state를 사용할 수 있습니다: ```tsx filename="pages/index.tsx" switcher import React, { useState, FormEvent } from 'react' @@ -247,7 +245,7 @@ export default function Page() { async function onSubmit(event: FormEvent) { event.preventDefault() - setIsLoading(true) // Set loading to true when the request starts + setIsLoading(true) // 요청이 시작되면 로딩 상태를 true로 설정 try { const formData = new FormData(event.currentTarget) @@ -256,14 +254,14 @@ export default function Page() { body: formData, }) - // Handle response if necessary + // 필요한 경우 응답 처리 const data = await response.json() // ... } catch (error) { // Handle error if necessary console.error(error) } finally { - setIsLoading(false) // Set loading to false when the request completes + setIsLoading(false) // 요청이 성공적으로 끝난 경우 로딩 상태를 false로 설정 } } @@ -286,7 +284,7 @@ export default function Page() { async function onSubmit(event) { event.preventDefault() - setIsLoading(true) // Set loading to true when the request starts + setIsLoading(true) // 요청이 시작되면 로딩 상태를 true로 설정 try { const formData = new FormData(event.currentTarget) @@ -295,14 +293,14 @@ export default function Page() { body: formData, }) - // Handle response if necessary + // 필요한 경우 응답 처리 const data = await response.json() // ... } catch (error) { // Handle error if necessary console.error(error) } finally { - setIsLoading(false) // Set loading to false when the request completes + setIsLoading(false) // 요청이 성공적으로 끝난 경우 로딩 상태를 false로 설정 } } @@ -319,7 +317,7 @@ export default function Page() { ### Redirecting -If you would like to redirect the user to a different route after a mutation, you can [`redirect`](/docs/pages/building-your-application/routing/api-routes#response-helpers) to any absolute or relative URL: +변형 후 사용자를 다른 라우트로 리디렉션하려는 경우, 모든 absolute URL 또는 relative URL로 [`redirect`](/docs/pages/building-your-application/routing/api-routes#response-helpers)할 수 있습니다: ```ts filename="pages/api/submit.ts" switcher import type { NextApiRequest, NextApiResponse } from 'next' @@ -342,7 +340,7 @@ export default async function handler(req, res) { ### Setting cookies -You can set cookies inside an API Route using the `setHeader` method on the response: +setHeader 메서드를 사용하여 API Route 내의 쿠키를 설정할 수 있습니다: ```ts filename="pages/api/cookie.ts" switcher import type { NextApiRequest, NextApiResponse } from 'next' @@ -365,7 +363,7 @@ export default async function handler(req, res) { ### Reading cookies -You can read cookies inside an API Route using the [`cookies`](/docs/pages/building-your-application/routing/api-routes#request-helpers) request helper: +[`cookies`](/docs/pages/building-your-application/routing/api-routes#request-helpers)를 사용하여 API Route 내의 쿠키를 읽을 수 있습니다: ```ts filename="pages/api/cookie.ts" switcher import type { NextApiRequest, NextApiResponse } from 'next' @@ -388,7 +386,7 @@ export default async function handler(req, res) { ### Deleting cookies -You can delete cookies inside an API Route using the `setHeader` method on the response: +setHeader 메서드를 사용하여 API Route 내의 쿠키를 삭제할 수 있습니다: ```ts filename="pages/api/cookie.ts" switcher import type { NextApiRequest, NextApiResponse } from 'next'