为什么我在访问 req.user.id 时遇到错误?

问题描述 投票:0回答:1

我在我的 Express、Node 项目上设置了护照身份验证。但是,当我访问 req.user 时,我收到错误

Property 'id' does not exist on type 'User'.ts(2339)
。 这是我的代码

员工.controller.ts

import { Request, Response } from 'express';


    export const createEmployee = async (req:Request, res: Response) => {
    const currentUser = req.user.id
    return responseSuccess(res, {newUser:req.body,user: currentUser});
  };

护照.ts

import passportJWT from "passport-jwt";
import jwt from "jsonwebtoken";
import env from "../../config/env";
import Employee from "../models/employee.model";
import { PassportStatic } from 'passport';

const { ExtractJwt } = passportJWT;
const JwtStrategy = passportJWT.Strategy;

export function passportConfiguration(passport:PassportStatic) {
    const opts: passportJWT.StrategyOptions = {
        secretOrKey: env.jwtSecret,
        jwtFromRequest: ExtractJwt.fromAuthHeaderWithScheme('Bearer'),
    };

  passport.use(
    new JwtStrategy(opts, async (jwtPayload, cb) => {
      const employee = await Employee.findOne({ _id: jwtPayload.id }).select('-password -otpSecret').exec();
     
      if (employee) {
        cb(null, employee);
      } else {
        cb(new Error("Something wrong in token"), false);
      }
    })
  );
}

export function generateToken(employee:any) {
  return jwt.sign({ id: employee._id, email: employee.email }, env.jwtSecret, {
    expiresIn: env.jwtExpiresIn,
  });
}

身份验证.ts

import passport from "passport";
import UnauthorizedError from "../common/http-errors/UnauthorizedError";
import InternalServerError from "../common/http-errors/InternalServerError";
import messages from "../common/messages";

export default async (req, res, next) => {
  passport.authenticate("jwt", {}, (error, user, info) => {
    if (error) {
      return next(new InternalServerError());
    }

    if (user) {
      req.user = user
      return next();
    }
    return next(new UnauthorizedError(messages.auth.invalidToken));
  })(req, res, next);
};

我尝试的是

  • 当我尝试删除
    Request
    上的
    req:Request
    时,错误消失了。但将 Type 放在 req 参数中是标准的。
  • 列表项
    const currentUser = req.user?.id
    仍然存在错误

我不确定这是否是 tsconfig 问题。这是我的 tsconfig.json

{
  "files": ["src/index.ts", "config/env.ts"],
  "compilerOptions": {
      /* Basic Options */
     
      "skipLibCheck": true,
      
      "resolveJsonModule": true,
      "target": "es5" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */,
      "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
      "lib": ["es2015", "es2017"] /* Specify library files to be included in the compilation. */,
      "allowJs": true /* Allow javascript files to be compiled. */,
      "checkJs": true /* Report errors in .js files. */,
      "sourceMap": true /* Generates corresponding '.map' file. */,
      "outDir": "./dist" /* Redirect output structure to the directory. */,
      "typeRoots": ["src/typings", "./node_modules/@types"],
      "strictBindCallApply": true /* Enable strict 'bind', 'call', and 'apply' methods on functions. */,
      "noImplicitThis": true /* Raise error on 'this' expressions with an implied 'any' type. */,
      "alwaysStrict": true /* Parse in strict mode and emit "use strict" for each source file. */,
      "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    
  },
  "include": ["server/typings/*.ts", "server/typings/customer.d.ts"]
}

抱歉添加了图片。只是为了表明id有下划线错误。

我一直不明白为什么。

javascript node.js typescript express passport.js
1个回答
0
投票

您正在使用

Request
模块中
express
的类型定义,该模块没有
user
属性,但仅在此处找到

© www.soinside.com 2019 - 2024. All rights reserved.