Nestjs의 POST 요청에서 모든 본문 값을 얻는 방법은 무엇입니까?
15300 단어 resource
body 메서드 요청에서 POST 값을 가져오려면 Nestjs의 @Body() 모듈에서 @nestjs/common 데코레이터 함수를 사용할 수 있습니다.TL; DR
import { Controller, Post, Body } from "@nestjs/common";
// DTO
import { PostDTO } from "../dto/post";
// the @Controller() decorator function will instruct Nestjs
// to add a route of `/posts`
@Controller("posts")
export class PostsController {
// Some Important Points 🌟
// 1.
// the @Post() decorator function will instruct Nestjs
// that this is the default method that should be
// invoked when the user requests a `POST` to `/posts` endpoint
// 2.
// Using `body` parameter to get the values
// from the body of the request
// 3.
// and the `Body()` decorator function will
// instruct Nestjs to bind the request `body` values to it.
// 4.
// Also using the `PostDTO` as the type for the `body` parameter.
@Post()
createPost(@Body() body: PostDTO) {
return `Created a new post with values of ${JSON.stringify(body)} 🚀`;
}
}
예를 들어
/posts라는 API 요청 엔드포인트를 만들고 이 엔드포인트에 대한 POST 메서드 요청 시 요청의 body 값을 기반으로 새 게시물을 생성해야 한다고 가정해 보겠습니다.이를 먼저 수행하려면
controller 끝점에 대해 /posts를 만든 다음 POST 끝점에 대한 /posts 요청이 있을 때 호출되어야 하는 메서드를 연결해야 합니다.다음과 같이 할 수 있습니다.
import { Controller, Post } from "@nestjs/common";
// the @Controller() decorator function will instruct Nestjs
// to add a route of `/posts`
@Controller("posts")
export class PostsController {
// the @Post() decorator function will instruct Nestjs
// that this is the default method that should be
// invoked when the user requests a `POST` to `/posts` endpoint
@Post()
createPost() {
return `Created a new post 🚀`;
}
}
Nestjs에서
POST 요청 엔드포인트 생성에 대한 자세한 내용은 How to make a simple POST request or an API endpoint in Nestjs? 블로그를 참조하십시오.POST 경로에 대한 /posts 메서드 요청 끝점을 만든 후 이제 body 메서드 내에서 createPost()라는 매개 변수를 사용할 수 있습니다.다음과 같이 할 수 있습니다.
import { Controller, Post, Body } from "@nestjs/common";
// the @Controller() decorator function will instruct Nestjs
// to add a route of `/posts`
@Controller("posts")
export class PostsController {
// Some Important Points 🌟
// 1.
// the @Post() decorator function will instruct Nestjs
// that this is the default method that should be
// invoked when the user requests a `POST` to `/posts` endpoint
// 2.
// Using `body` parameter to get the values
// from the body of the request
@Post()
createPost(body) {
return `Created a new post with values of ${JSON.stringify(body)} 🚀`;
}
}
문제는 Nestjs 런타임이
body 메서드의 createPost() 매개변수에 어떤 값을 주입해야 하는지 알지 못한다는 것입니다. 요청에서 body 값이 필요하다고 Nestjs에 지시하려면 @Body() 매개변수 앞에 @nestjs/common 모듈의 body 데코레이터 함수를 사용해야 합니다. 이렇게 하면 요청의 body 값이 body 메서드의 createPost() 매개변수에 바인딩됩니다.다음과 같이 할 수 있습니다.
import { Controller, Post, Body } from "@nestjs/common";
// the @Controller() decorator function will instruct Nestjs
// to add a route of `/posts`
@Controller("posts")
export class PostsController {
// Some Important Points 🌟
// 1.
// the @Post() decorator function will instruct Nestjs
// that this is the default method that should be
// invoked when the user requests a `POST` to `/posts` endpoint
// 2.
// Using `body` parameter to get the values
// from the body of the request
// 3.
// and the `Body()` decorator function will
// instruct Nestjs to bind the request `body` values to it.
@Post()
createPost(@Body() body) {
return `Created a new post with values of ${JSON.stringify(body)} 🚀`;
}
}
이제 TypeScript를 사용하고 있으므로 TypeSript는
body 매개변수에 대해 어떤 유형도 사용하지 않기 때문에 오류를 표시할 수 있습니다.이를 해결하기 위해 Nestjs에서
DTO(일명 Data Transfer Object)라는 것을 생성할 수 있습니다. 간단히 말해서 요청에서 class의 값을 정의하는 abody입니다. class 대신 interface를 사용하는 이유를 물을 수 있습니다. 이는 class가 이제 JavaScript 사양 내에서 표준이며 body 값에 대한 런타임 검사를 제공하기 때문입니다. 다음 블로그 게시물에서 Nestjs 내의 본문 값 유효성 검사에 대해 논의할 것입니다. (출간 후 링크해드리겠습니다 🤞🏽).dto라는 새 디렉토리를 만들고 post.ts라는 파일을 만듭니다. 터미널 내에서 이것을 만들려면 다음 명령을 사용하십시오.mkdir dto && touch ./dto/post.ts
이제 디렉토리 계층 구조는 다음과 같습니다.
- dto
- post.ts
- post
- posts.controller.ts
post.ts 파일 내에서 class, PostDTO 및 title 유형의 description라는 기본 필드가 있는 content라는 string를 생성해 보겠습니다.다음과 같이 할 수 있습니다.
dto/post.ts 파일
// Post DTO (aka Data transfer Object)
// with some basic fields
class PostDTO {
title: string;
description: string;
content: string;
}
export { PostDTO };
이제
DTO 엔드포인트에 대해 잘 정의된 /posts가 있으므로 이를 body 클래스의 createPost() 메서드에서 PostsController 매개변수의 유형으로 사용하겠습니다.import { Controller, Post, Body } from "@nestjs/common";
// DTO
import { PostDTO } from "../dto/post";
// the @Controller() decorator function will instruct Nestjs
// to add a route of `/posts`
@Controller("posts")
export class PostsController {
// Some Important Points 🌟
// 1.
// the @Post() decorator function will instruct Nestjs
// that this is the default method that should be
// invoked when the user requests a `POST` to `/posts` endpoint
// 2.
// Using `body` parameter to get the values
// from the body of the request
// 3.
// and the `Body()` decorator function will
// instruct Nestjs to bind the request `body` values to it.
// 4.
// Also using the `PostDTO` as the type for the `body` parameter.
@Post()
createPost(@Body() body: PostDTO) {
return `Created a new post with values of ${JSON.stringify(body)} 🚀`;
}
}
이제
POST , /posts 및 title 필드가 있는 description 요청을 content 엔드포인트로 보내면 게시물이 우리가 제공한 필드로 생성되었다는 응답을 볼 수 있습니다.Nestjs의
body 요청에서 POST 값을 성공적으로 얻었습니다.codesandbox에 있는 위의 코드를 참조하십시오.
Hoppscotch API tester 🚀으로 이동하여 위의 codesandbox 컨테이너에 있는 URL로 POST 요청을 보냅니다.
참고: 위의 Hoppscotch URL을 사용하여 요청을 보낼 수 없는 경우 앱에서 프록시를 켜십시오.
그게 다야 😃!
이 정보가 유용하다고 생각되면 자유롭게 공유하세요 😃.
Reference
이 문제에 관하여(Nestjs의 POST 요청에서 모든 본문 값을 얻는 방법은 무엇입니까?), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/melvin2016/how-to-get-all-the-body-values-from-a-post-request-in-nestjs-3llm텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)