我尝试创建两个中间件,一个是身份验证中间件,另一个是检查用户数据库中的“isAdmin”是否为真的中间件。身份验证中间件工作正常,但为了让管理中间件工作,我尝试在其中放入req.users = data;
,但它返回错误:
Property 'users' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.ts(2339)
认证中间件:
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
interface TokenPayload {
id: string;
iat: number;
exp: number;
}
export default async function authMiddleware(
req: Request, res: Response, next: NextFunction
) {
const { authorization } = req.headers;
if (!authorization) {
return res.status(401).json('Invalid Authorization');
};
const token = authorization.replace('Bearer', ' ').trim();
try {
const secret = process.env.JWT_SECRET as string;
const data = jwt.verify(token, secret);
req.users = data;
const { id } = data as TokenPayload;
req.userId = id;
return next();
} catch (err) {
return res.status(401).json(err);
}
}
在auth中间件管理中,它在用户中返回相同的错误
Property 'users' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.ts(2339)
身份验证中间件管理
import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
import authMiddleware from './AuthMiddlewares';
export default async function authAdminMiddleware(
req: Request, res: Response, next: NextFunction,
) {
authMiddleware(req, res, () => {
if (req.users.isAdmin) {
next();
} else {
res.status(403).json("You are not alowed to do that!");
}
})
}
1条答案
按热度按时间7jmck4yq1#
可以使用declaration merging在
req
对象中声明附加属性users
:(See也称为here。)