TypeScript中从JWT中间件传数据及解决req.user未定义问题
解决TypeScript中Express req.user未定义的问题
在TypeScript环境下,Express的Request类型默认不包含user属性,你需要通过扩展全局Express类型来添加这个属性,具体实现步骤如下:
1. 创建类型声明文件
在项目中新建一个类型定义文件(比如src/types/express.d.ts),用于扩展Express的Request接口:
// 引入Express原有类型 import { Request } from 'express'; // 定义JWT解码后的用户信息类型,根据你的Token实际存储字段调整 interface User { id: string; username: string; // 其他你存在Token中的字段 } // 扩展Express的Request接口,添加user属性 declare global { namespace Express { interface Request { user: User; } } }
2. 配置TypeScript识别声明文件
确保tsconfig.json的include数组包含该类型文件路径,让TypeScript能加载这个扩展声明:
{ "compilerOptions": { // 其他编译配置... "typeRoots": ["./node_modules/@types", "./src/types"] }, "include": ["src/**/*"] }
3. 修正中间件代码(含错误处理)
注意jwt.verify验证失败时会抛出错误,需要用try-catch捕获,同时给解码结果指定类型:
import { Request, Response, NextFunction } from 'express'; import jwt from 'jsonwebtoken'; // 引入自定义的User类型 import { User } from '../types/express'; const authorized = (req: Request, res: Response, next: NextFunction) => { try { const token = req.header('token'); if (!token) { return res.status(401).send('No token, authorization denied!'); } // 强制指定解码结果的类型为User const decoded = jwt.verify(token, process.env.ACCESS_TOKEN_SECRET!) as User; // 此时req.user已被TypeScript识别,可正常赋值 req.user = decoded; next(); } catch (err) { res.status(400).send('Token is not valid!'); } };
4. 在控制器中使用req.user
后续控制器函数里可以直接访问req.user,TypeScript会自动识别它的类型并提供字段提示:
const getUserProfile = (req: Request, res: Response) => { res.json({ userId: req.user.id, username: req.user.username }); };
这样既能解决req.user未定义的类型报错问题,也能保证代码的类型安全性。
内容的提问来源于stack exchange,提问作者Bigbool98
相关产品推荐
相关产品推荐

