Nest.js
nest 미들웨어 사용할때 , 무한로딩 고치는 법
혬00
2023. 8. 14. 06:22
데이터는 CRUD 모두 들어갔고 , 확인도 되지만 , 무한로딩될 때 고치는 법
대부분의 nest 개발자가 node 를 사용하다가 넘어왔을것이다.
필자는 node 를 사용할때 미들웨어를 통해 넘어오는 값들을 response로 받아왔었고 , 실제로 테스트 할때도 문제가 없었다. 하지만 nest 를 처음 사용하면서 기존에 되는것들이 안되는게 많았다
해결 방법은 request 로 받아와주면 된다
이렇게 해결하고 생각해보니까 지금까지 왜 res 로 받아왔는지 모르겠다
그냥 되니까 했었다 ...
req = 요청 , res = 응답 다시 한번 새기자 !
컨트롤러
@Post('/member')
async createMember(@Body() MemberData: createMemberDto, @Request() req) {
const myUid = req.user.uid;
const result = await this.MembersService.createMember(MemberData, myUid);
return { message: '멤버 추가에 성공하였습니다', data: result };
}
미들웨어에서 내보내줄때는
@Injectable()
export class AuthMiddleware implements NestMiddleware {
constructor(private jwtService: JwtService) {}
async use(req: any, res: any, next: Function) {
const authHeader = req.cookies;
if (!authHeader) {
throw new UnauthorizedException('JWT not found');
}
let token: string;
try {
const authkey = authHeader.Authentication;
const [authType, token] = authkey.split(' ');
if (authType !== 'Bearer' || !token) {
throw new UnauthorizedException('It is not Bearer type of token or abnormal token');
}
const payload = await this.jwtService.verify(token);
req.user = payload;
next();
} catch (err) {
throw new UnauthorizedException(`Invalid JWT: ${token}`);
}
}
}
이렇게 !
참고로 next() 안써도 무한로딩 된다.
무한로딩 에러 검색해보니 next 안쓴 케이스가 가장 많았다 !