我在我的 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"]
}
我一直不明白为什么。