0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

NestJSでresponse headerを変更する

Posted at

何したかった

paginationでheader情報にcurrentPageとか格納したい

わからなかった部分

header情報を動的に変えたかった

実装

hogeコンポーネントがある状態

決まったheader情報を返したい場合

@Headerを使用する
次のコードは"Page": "1"がheaderに格納される

hoge.controller.ts
import {
  Controller,
  Get,
  HttpCode,
  Param,
  UseGuards,
  Header,
} from '@nestjs/common';
import { HogeService } from './hoge.service';

export class HogeController {
  constructor(private readonly service: HogeService) {}

  @Get()
  @HttpCode(200)
  @Header('Page', '1')
  async list(@Param() request: IdRequest): Promise<Hoge[]> {
    return await this.service.list(request);
  }
}

動的にheader情報を変更したい場合

@Res() res: Response を使用してheader情報を変更する
次のコードは"Page": "123"がheaderに格納される

[注意点]
import { Response } from 'express'; をしないといけない
res.send()しないとリクエストがタイムアウトする

hoge.controller.ts
import {
  Controller,
  Get,
  HttpCode,
  Param,
  UseGuards,
  Res,
} from '@nestjs/common';
import { HogeService } from './hoge.service';
import { Response } from 'express';

export class HogeController {
  constructor(private readonly service: HogeService) {}

  @Get()
  @HttpCode(200)
  async list(
    @Param() request: IdRequest, 
    @Res() res: Response,
  ): Promise<Response> {
    res.set('Page', '123');
    return res.send(await this.service.list(request));
  }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?