Как установить или отправить статический код статуса ответа для POST запроса в Nestjs?

Первоначально было опубликовано здесь!

Чтобы установить или отправить статический код состояния ответа для POST запроса в Nestjs, мы можем использовать функцию-декоратор @HttpCode() из модуля @nestjs/common перед методом класса Controller, который обрабатывает этот POST запрос.

TL;DR

// import `HttpCode` decoration function from the `@nestjs/common` module
import { Controller, Post, HttpCode } from "@nestjs/common";

// the @Controller() decorator function will instruct Nestjs
// to add a route of `/greet`
@Controller("greet")
export class GreetController {
  // 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 `/greet` endpoint
  // 2. Using the @HttpCode() decoration and passing
  // the `204` status code as its argument to set
  // the static status code for this `POST` request
  @Post()
  @HttpCode(204)
  sayHello() {
    return `Hello World`;
  }
}
Войти в полноэкранный режим Выйти из полноэкранного режима

Допустим, у нас есть конечная точка API POST под названием /greet, и при запросе к ней нам нужно получить ответ со статическим кодом состояния 204 (No Content).

Для этого сначала мы можем создать класс Controller и определить конечную точку запроса POST следующим образом,

import { Controller, Post } from "@nestjs/common";

// the @Controller() decorator function will instruct Nestjs
// to add a route of `/greet`
@Controller("greet")
export class GreetController {
  // the @Post() decorator function will instruct Nestjs
  // that this is the default method that should be
  // invoked when the user requests a `POST` to `/greet` endpoint
  @Post()
  sayHello() {
    return `Hello World`;
  }
}
Войти в полноэкранный режим Выход из полноэкранного режима

Чтобы узнать больше о создании POST запроса в Nestjs, смотрите блог Как сделать простой POST запрос или конечную точку API в Nestjs?

Теперь давайте также импортируем функцию-декоратор @HttpCode() из модуля @nestjs/common и используем ее прямо над методом sayHello().

После этого нам нужно передать статический код состояния, в нашем случае 204 (тип number) в качестве аргумента функции-декоратора @HttpCode(). Этот код состояния будет отправлен вместе с ответом.

Это можно сделать следующим образом,

// import `HttpCode` decoration function from the `@nestjs/common` module
import { Controller, Post, HttpCode } from "@nestjs/common";

// the @Controller() decorator function will instruct Nestjs
// to add a route of `/greet`
@Controller("greet")
export class GreetController {
  // 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 `/greet` endpoint
  // 2. Using the @HttpCode() decoration and passing
  // the `204` status code as its argument to set
  // the static status code for this `POST` request
  @Post()
  @HttpCode(204)
  sayHello() {
    return `Hello World`;
  }
}
Войти в полноэкранный режим Выйти из полноэкранного режима

Мы успешно установили статический код состояния ответа для запроса POST в Nestjs. Ура 🥳!

Посмотрите приведенный выше код в реальном времени в codesandbox.

Посетите этот URL Hoppscotch и посмотрите, возвращается ли код состояния 204 вместе с ответом.

Вот и все 😃!

Не стесняйтесь делиться информацией, если она оказалась полезной 😃.


Оцените статью
devanswers.ru
Добавить комментарий