TS2339:类型“请求”上不存在属性“用户”

时间:2020-10-06 23:08:54

标签: typescript express nestjs jwt-auth passport-jwt

我正在尝试使用JwtAuthGuard区分已认证的请求和未认证的请求。

我确实遵循了official Nestjs documentation on authentification,但是由于出现打字错误,我无法使其工作:TS2339: Property 'user' does not exist on type 'Request'.

bookmarks.controller.ts

import { Controller, Get, Req, UseGuards } from '@nestjs/common'
import { BookmarksService } from './bookmarks.service'
import { StandardSuccessResponse } from '../utils/standard-response.type'
import { ResponseMessage } from '../utils/response-messages.enum'
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard'

@Controller('v1/bookmarks')
export class BookmarksController {
  constructor(private bookmarksService: BookmarksService) {}

  @UseGuards(JwtAuthGuard)
  @Get()
  async getAllBookmarkedJobs(
    @Req() request: Request
  ): Promise<StandardSuccessResponse<string[]>> {
    return {
      success: true,
      data: await this.bookmarksService.getAllBookmarkedJobs(
        request.user.candidateId
      ),
      meta: null,
      message: ResponseMessage.BOOKMARKS_RETRIEVED,
    }
  }
}

strategies/jwt.strategy.ts

import { ExtractJwt, Strategy } from 'passport-jwt'
import { PassportStrategy } from '@nestjs/passport'
import { Injectable } from '@nestjs/common'

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: process.env.JWT_SECRET,
    })
  }

  async validate(payload: any) {
    return { candidateId: payload.sub }
  }
}

3 个答案:

答案 0 :(得分:1)

user属性通过Request附加到@types/passport对象,或者使用extends Request的自定义接口并自己添加类型,例如:

export interface RequestWithUser extends Request {

  user: UserType;
}

答案 1 :(得分:1)

因为您没有从Express中导入请求,所以只需添加:

import { Request } from 'express';

但是您需要安装@types/passport@types/express,它才能正常工作。

答案 2 :(得分:-1)

由于要获取数据,因此应将@Req()更改为@Res()。

     @UseGuards(JwtAuthGuard)
     @Get()
     async getAllBookmarkedJobs(@Res() res): Promise<StandardSuccessResponse<string[]> {
        return {
          success: true,
          data: await this.bookmarksService.getAllBookmarkedJobs(
           res.user.candidateId
          ),
          meta: null,
          message: ResponseMessage.BOOKMARKS_RETRIEVED,
        }
     }