Первоначально было опубликовано здесь!
Чтобы установить или отправить статический заголовок для GET
запроса в Nestjs, мы можем использовать функцию-декоратор @Header()
из модуля @nestjs/common
перед методом класса Controller
, который обрабатывает этот GET
запрос.
TL;DR
// import `@Header()` decorator function from the `@nestjs/common` module
import { Controller, Get, Header } 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. use the @Header() decorator function and
// pass the header name as the first argument
// and the header value as the second argument
@Get()
@Header("x-app-name", "MyApp")
sayHello() {
return `Hello World`;
}
}
Например, допустим, у нас есть конечная точка API под названием /greet
, и запрос к ней даст нам ответ Hello World
.
Это можно сделать следующим образом,
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
в Nestjs, смотрите блог Как сделать простой GET запрос или конечную точку API в Nestjs?
Теперь, если нам нужно отправить пользовательский заголовок x-app-name
со значением My App
, мы можем использовать функцию-декоратор @Header()
и использовать прямо над методом sayHello()
.
Функция-декоратор @Header()
принимает 2 аргумента:
- первый аргумент должен быть именем заголовка
- и второй аргумент — значение заголовка.
В нашем случае это будет выглядеть следующим образом,
// import `@Header()` decorator function from the `@nestjs/common` module
import { Controller, Get, Header } 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. use the @Header() decorator function and
// pass the header name as the first argument
// and the header value as the second argument
@Get()
@Header("x-app-name", "MyApp")
sayHello() {
return `Hello World`;
}
}
Теперь, если мы отправим запрос GET
на конечную точку API /greet
, мы получим ответ Hello World
вместе с заголовком x-app-name
, имеющим значение MyApp
.
Мы успешно установили статический заголовок ответа для запроса GET
в Nestjs. Ура 🥳!
Посмотрите приведенный выше код в реальном времени в codesandbox.
Чтобы увидеть заголовок в ответе, перейдите по этой ссылке Hoppscotch и сделайте запрос.
Вот и все 😃!
Не стесняйтесь поделиться, если вам это было полезно 😃.