How write header with nestjs

17,662

Solution 1

NestJS is build on top of express, so do it like in express:

async login(@Body('username') username: string, @Body('password') password: string, @Res() res: Response) {
    const token = await this.authService.validateUser(username, password);
    res.set('Authorization', 'Bearer ' + token);
    res.send({
        success: true,
        token,
    })
});

Solution 2

In latest versions you could use the @Header decorator within NestJS Core.

import { Controller, Get, Req, Header, Res } from '@nestjs/common';
import { Request, Response } from 'express';

@Controller('cookies')
export class CookiesController {
  @Get('set')
  // @Header('Set-Cookie', 'cookieName = 12345') // "Usin header decorator"
  setCookie(@Res() response: Response): Response {
    /*
    * If using express approach, pass @Res as param decorator
    */
    response.cookie('rememberme', '1') // Using express res object.
    return response.send('Cookie has been set! :)')
  }

  @Get()
  checkCookie(@Req() request: Request ): string {
    console.log(Object.keys(request.cookies))
    if(Object.keys(request.cookies).length > 0){
      console.log('cookies =>', request.cookies)
      return 'Cookies are set :)'
    } else {
      return 'Uh, oh! Cookie hasn\'t been set :\'('
    }
  }
}

Share:
17,662

Related videos on Youtube

Walter Armando Cruz
Author by

Walter Armando Cruz

Updated on September 14, 2022

Comments

  • Walter Armando Cruz
    Walter Armando Cruz over 1 year

    how I can write headers using way nest.js?

    I'm currently using this:

    import { Controller, Body, Get, Post, HttpCode, HttpStatus, Req, Res } from '@nestjs/common';
    import { Request, Response } from 'express';
    import { AuthService } from './auth.service';
    import { Usuario } from '../usuario/usuario.entity';
    import { JsonWebTokenError } from 'jsonwebtoken';
    import { request } from 'http';
    
    @Controller('auth')
    export class AuthController {
        constructor(private readonly authService: AuthService) { }
    
        @Post('login')
        @HttpCode(HttpStatus.OK)
        async login(@Body('username') username: string, @Body('password') password: string, @Res() response: Response) {
            this.authService
                .validateUser(username, password)
                .then((token) => {
                    response.setHeader('Authorization', 'Bearer ' + token);
    
                    let respuesta: any = {};
                    respuesta.success = true;
                    respuesta.token = token;
    
                    return response.send(respuesta);
                });
        }
    }
    

    I do not want to use response.setHeader('Authorization', 'Bearer ' + token); and return response.send(respuesta);

    Thanks for your answers!

  • DoronG
    DoronG about 4 years
    your answer did not provide a solution. The Header decorator is for reading a header and not setting it. Plus, your code example has it commented out.
  • manu_unter
    manu_unter almost 4 years
    @DoronG I have to object here, although I understand the confusion. There is a @Header decorator which sets response headers, and it is used on controller methods. But there is also a @Headers (note the plural) decorator which can be used on controller method parameters, and that one will inject a request header as an argument. See docs.nestjs.com/controllers#headers and docs.nestjs.com/controllers#request-object respectively
  • DoronG
    DoronG almost 4 years
    @manuhornung You are correct. I must admit I was confused. Thank you for the clarification. I have tried to change my vote, but can only do so if the original answer is edited. Can you edit your answer to clarify it as well?