NestJS中,如何在程序其他类中,不传递 header 对象的情况下,如何能得到 HTTP Request 数据方便处理,类似 Java SpringBoot 中的 RequestContextHolder ?
用下面的方法即可:
1. 在你的类上,使用 @Injectable({ scope: Scope.REQUEST })
2. 构造方法中,增加 @Inject(REQUEST) private readonly request: Request
3. 类中就可以随时使用 http request 而无需传递对象了
import { Inject, Injectable, Scope } from "@nestjs/common";
import { REQUEST } from "@nestjs/core";
@Injectable({ scope: Scope.REQUEST })
export class XxxService {
constructor(@Inject(REQUEST) private readonly request: Request) { }
getToken(): any {
const s_token = this.request.headers['token'];
if (s_token) {
return JSON.parse(s_token);
}
return null;
}
getInfo(): string {
let result = (this.request as any).locals?.info;
if (result) {
return result
}
const token = this.getToken();
if (token) {
return null;
}
result = convertToken(token);
this.request['locals'].info = result;
return result;
}
}