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

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

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

TL;DR

// import `@Redirect()` decorator function from the `@nestjs/common` module
import { Controller, Get, Redirect } from "@nestjs/common";

// the @Controller() decorator function will instruct Nestjs
// to add a route of `/greet`
@Controller("greet")
export class GreetController {
  // 1. the @Get() decorator function will instruct Nestjs
  // that this is the default method that should be
  // invoked when the user requests a `GET` to `/greet` endpoint
  // 2. Using the @Redirect() decorator function to have static redirection
  // and passing the redirect url as the first argument and
  // the redirection status code as the second argument
  @Redirect("https://www.google.com/", 301)
  @Get()
  sayHello() {
    return `Hello World`;
  }
}
Войти в полноэкранный режим Выйти из полноэкранного режима

Например, допустим, у нас есть конечная точка API запроса GET под названием /greet, и при запросе она дает нам ответ Hello World.

Код для конечной точки API будет выглядеть следующим образом,

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

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

Теперь, что если нам нужно статически перенаправить запросы GET на другой URL? Допустим, это будет https://www.google.com/.

Для этого мы можем использовать функцию-декоратор @Redirect() из модуля @nestjs/common и вызвать ее прямо над методом класса Controller, который обрабатывает запрос GET. В нашем случае это метод sayHello().

Функция декоратора Redirect() также принимает 2 аргумента, оба из которых являются необязательными:

  • первый аргумент — это URL, на который нужно перенаправить. В нашем случае это URL https://www.google.com/.
  • а второй аргумент — это код статуса перенаправления. В нашем случае это 301 в качестве кода статуса. Подробнее о кодах состояния перенаправления.

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

// import `@Redirect()` decorator function from the `@nestjs/common` module
import { Controller, Get, Redirect } from "@nestjs/common";

// the @Controller() decorator function will instruct Nestjs
// to add a route of `/greet`
@Controller("greet")
export class GreetController {
  // 1. the @Get() decorator function will instruct Nestjs
  // that this is the default method that should be
  // invoked when the user requests a `GET` to `/greet` endpoint
  // 2. Using the @Redirect() decorator function to have static redirection
  // and passing the redirect url as the first argument and
  // the redirection status code as the second argument
  @Redirect("https://www.google.com/", 301)
  @Get()
  sayHello() {
    return `Hello World`;
  }
}
Войти в полноэкранный режим Выйти из полноэкранного режима

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

Посмотрите приведенный выше код в прямом эфире в codesandbox.

Вы также можете перейти по URL https://q85sh3.sse.codesandbox.io/greet и увидеть, что он перенаправляется на главную страницу Google.

Вот и все 😃.

Не стесняйтесь поделиться, если вы нашли это полезным 😃.


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