【发布时间】:2020-05-21 13:46:45
【问题描述】:
我无法从装饰巢的请求中获取用户,请帮助我。 中间件运行良好,它通过令牌找到用户并将用户保存在请求中 我的中间件:
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);
}
}
【问题讨论】:
-
你的 Nest common 和 core 版本是什么?
-
@JayMcDoniel 6.11.11
-
嗯,那是那个工厂的正确版本。你检查过你的
req在装饰器中是什么吗?我看不出有什么问题。 -
是的,在用户装饰器中我有另一个请求,但我不知道为什么
-
我发现,用户是在 req.raw.user 中设置的
标签: javascript typescript nestjs