Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How write header with nestjs

Tags:

header

nestjs

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!

like image 400
Walter Armando Cruz Avatar asked Apr 23 '18 15:04

Walter Armando Cruz


People also ask

How do I get headers in Nestjs?

Headers. To specify a custom response header, you can either use a @Header() decorator or a library-specific response object (and call res. header() directly). Hint Import Header from the @nestjs/common package.

How do I post on Nestjs?

To upload a single file, simply tie the FileInterceptor() interceptor to the route handler and extract file from the request using the @UploadedFile() decorator. Hint The FileInterceptor() decorator is exported from the @nestjs/platform-express package. The @UploadedFile() decorator is exported from @nestjs/common .


1 Answers

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,
    })
});
like image 125
Valera Avatar answered Oct 07 '22 09:10

Valera