Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Nest.js's @Headers properly?

According to the controller docs I can use @Headers(param?: string) or req.headers or req.headers[param] to get header value. I tried the first approach, I have following in my request headers from Postman

Content-Type:application/json
My-Id:test12345

I have following controller sample code

@Put('/aa/:aa/bb/:bb/')
@UsePipes(new ValidationPipe({ transform: true }))
public async DoMyJob(@Body() request: MyRequestDto,
                                @Param('aa') aa: number,
                                @Param('bb') bb: string,
                                @Headers('My-Id') id: string): Promise<MyResponseDto> {
    // More code here
}

When I set break point to inspect the value from My-Id header it is undefined.

So how shall I do in Nest.Js properly to get the header value from RESTful service client?

like image 634
hardywang Avatar asked Jan 07 '19 20:01

hardywang


1 Answers

Headers will be sent in lower case so you need @Headers('my-id') instead.


Easy to debug by injecting the full headers object:

import { Headers } from '@nestjs/common';
...
@Put('/')
public async put(@Headers() headers) {
    console.log(headers);
}

The headers variable will then refer to the req.headers.

like image 185
Kim Kern Avatar answered Oct 18 '22 15:10

Kim Kern