我无法从装饰器嵌套的请求中获取用户,请帮助我。 中间件很好,它可以按令牌查找用户并在请求中保存用户 我的中间件:
import { Injectable, NestMiddleware, HttpStatus } from '@nestjs/common';
import { HttpException } from '@nestjs/common/exceptions/http.exception';
import { Request, Response } from 'express';
import { AuthenticationService } from '../modules/authentication-v1/authentication.service';
@Injectable()
export class AuthenticationMiddleware implements NestMiddleware {
constructor(
private readonly authenticationService : AuthenticationService
) {
}
async use(req: Request, res: Response, next: Function) {
let token = req.headers;
if(!token) {
throw new HttpException('token is required', 401);
}
if (!token.match(/Bearer\s(\S+)/)) {
throw new HttpException('Unsupported token', 401);
}
const [ tokenType, tokenValue ] = token.split(' ');
try {
const result = await this.authenticationService.getAccessToken(tokenValue);
req.user = result;
next();
} catch (e) {
throw new HttpException(e.message, 401);
}
}
}
但是这里请求没有属性用户,我也不知道为什么 用户装饰器:
export const User = createParamDecorator((data: any, req) => {
return req.user; // but here user undefined
});
应用程序模块:
export class AppModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(AuthenticationMiddleware)
.forRoutes({ path: 'auto-reports-v1', method: RequestMethod.GET });
}
}
路由方法:
@UseInterceptors(LoggingInterceptor)
@Controller('auto-reports-v1')
@ApiTags('auto-reports-v1')
export class AutoReportsController {
constructor(private readonly autoReportsService: AutoReportsService) {}
@Get()
async findAll(
@Query() filter: any,
@User() user: any): Promise<Paginated> {
return this.autoReportsService.findPaginatedByFilter(filter, user);
}
}
答案 0 :(得分:2)
在带有Fastify的NestJS中,中间件将值附加到req.raw
。这是因为中间件在请求被FastifyRequest
对象包装之前运行,因此所有值附件都被附加到IncomingRequest
对象(与Express Request对象相同)。然后,Fastify将IncomingRequest
包装在其自己的FastifyRequest
对象中,并通过IncomingRequest
公开req.raw
,这意味着您要查找的用户位于req.raw.user
而不是{{ 1}}。如果您希望Express和Fastify拥有相同的功能,建议您改用Guard。