Javascript 如何从嵌套中的请求获取用户?
我无法从decorator nest的请求中获取用户,请帮助我。 中间件工作良好,它通过令牌找到用户并在请求中保存用户 我的中间件:Javascript 如何从嵌套中的请求获取用户?,javascript,typescript,nestjs,Javascript,Typescript,Nestjs,我无法从decorator nest的请求中获取用户,请帮助我。 中间件工作良好,它通过令牌找到用户并在请求中保存用户 我的中间件: import { Injectable, NestMiddleware, HttpStatus } from '@nestjs/common'; import { HttpException } from '@nestjs/common/exceptions/http.exception'; import { Request, Response } from 'e
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);
}
}
@UseInterceptors(LoggingInterceptor)
@控制器('auto-reports-v1')
@ApiTags('auto-reports-v1')
导出类自动报告控制器{
构造函数(专用只读自动报告服务:自动报告服务){}
@得到()
异步findAll(
@Query()过滤器:任意,
@User()用户:任意):承诺{
返回此.autoReportsService.findPaginatedByFilter(filter,user);
}
}
在带有Fastify的NestJS中,中间件将值附加到req.raw
。这是因为中间件在请求被FastifyRequest
对象包装之前运行,所以所有的值附件都被附加到IncomingRequest
对象(与Express请求对象相同)。然后,Fastify将IncomingRequest
包装在自己的FastifyRequest
对象中,并通过req.raw
公开IncomingRequest
,这意味着您要查找的用户位于req.raw.user
而不是req.user
。如果您想在Express和Fastify中拥有相同的功能,我建议您使用一个防护装置 你的Nest common和core版本是什么?@JayMcDoniel 6.11.11Hmm,这是该工厂的正确版本。您是否检查了装饰器中的req
?是的,在user decorator中我有另一个请求,但我没有找到,用户是在req.raw.user中设置的