使用routing-controllers的@UseBefore装饰器时extractJWT中间件出现TypeScript编译错误求助
@UseBefore Decorator Let's break down your issue and walk through the most likely fixes:
Problem Recap
You're hitting TypeScript compile errors only when attaching your extractJWT middleware to a controller using routing-controllers' @UseBefore decorator. Without the decorator, your code compiles fine. The errors point to line 11 of your middleware file:
TSError: ⨯ Unable to compile TypeScript src/middleware/extractJWT.ts (11,43): Expression expected. (1109) src/middleware/extractJWT.ts (11,57): ':' expected. (1005)
Your Middleware Code
const extractJWT = (req: Request, res: Response, next: NextFunction) => { logging.info(NAMESPACE, "Validating Token"); let token = req.headers.authorization?.split(" ")[1]; if (token) { jwt.verify(token, config.server.token.secret, (error, decoded) => { if (error) { return res.status(404).json({ message: error.message, error }); } else { res.locals.jwt = decoded; next(); } }); } else { return res.status(401).json({ message: "Unauthorized" }); } }; export default extractJWT;
Controller Code
@Get("/validate") @UseBefore(extractJWT) async validate(@Req() req: Request, @Res() res: Response, next: NextFunction) { logging.info(NAMESPACE, "Token Validated"); return res.status(200).json({ message: "Authorized" }); }
Likely Fixes
1. Fix TypeScript Compiler Config for Decorators
Routing-controllers relies heavily on decorator syntax, which isn't enabled by default in TypeScript. The decorator might be triggering stricter type checks that your current config doesn't handle.
Update your tsconfig.json to include these mandatory settings:
{ "compilerOptions": { "experimentalDecorators": true, "emitDecoratorMetadata": true, "target": "ES6", // Or higher (ES2020+) "module": "CommonJS", // Match your project's module system "strict": true // Optional but recommended for catching type issues early } }
experimentalDecorators: Enables support for decorator syntaxemitDecoratorMetadata: Required for routing-controllers to reflect metadata about your routes and middleware
2. Align Middleware with Routing-Controllers' Interface
Instead of using a plain function, implement the ExpressMiddlewareInterface provided by routing-controllers. This ensures type compatibility with the framework's decorator system:
import { ExpressMiddlewareInterface } from "routing-controllers"; import jwt from "jsonwebtoken"; class ExtractJWT implements ExpressMiddlewareInterface { use(req: Request, res: Response, next: NextFunction) { logging.info(NAMESPACE, "Validating Token"); let token = req.headers.authorization?.split(" ")[1]; if (token) { jwt.verify(token, config.server.token.secret, (error: jwt.VerifyErrors | null, decoded: any) => { if (error) { // Note: 404 is for missing resources; use 401 for auth failures return res.status(401).json({ message: error.message, error }); } else { res.locals.jwt = decoded; next(); } }); } else { return res.status(401).json({ message: "Unauthorized" }); } } } export default new ExtractJWT();
Then update your controller to use the class:
@Get("/validate") @UseBefore(ExtractJWT) async validate(@Req() req: Request, @Res() res: Response) { logging.info(NAMESPACE, "Token Validated"); return res.status(200).json({ message: "Authorized" }); }
3. Fix Implicit Type Issues in Your Middleware
Even if the code works without the decorator, the decorator might expose hidden type problems. Try:
- Adding explicit types to the
jwt.verifycallback parameters (as shown in the code above) - Checking for typos or syntax errors on line 11 of your middleware (the error lines might be off due to formatting, so double-check brackets, commas, and variable names)
Quick Note on HTTP Status Codes
You're returning 404 when token verification fails—this is semantically incorrect. Use 401 Unauthorized for missing/invalid tokens, and reserve 404 for when a resource can't be found.
内容的提问来源于stack exchange,提问作者codestomping

