8

如何使用方式nest.js 编写标题?

我目前正在使用这个:

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);
            });
    }
}

我不想使用response.setHeader('Authorization', 'Bearer ' + token);return response.send(respuesta);

感谢您的回答!

4

2 回答 2

7

NestJS 是建立在 express 之上的,所以就像在 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,
    })
});
于 2018-04-25T08:35:55.870 回答
6

在最新版本中,您可以@Header在 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 :\'('
    }
  }
}

于 2019-04-22T04:15:18.967 回答