NodeJS 创建verifyTokenAdmin中间件时出错

bogh5gae  于 2022-12-22  发布在  Node.js
关注(0)|答案(1)|浏览(148)

我尝试创建两个中间件,一个是身份验证中间件,另一个是检查用户数据库中的“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!");
        }
    })
}
7jmck4yq

7jmck4yq1#

可以使用declaration mergingreq对象中声明附加属性users

declare global {
  namespace Express {
    interface Request {
      users: any
    }
  }
}

(See也称为here。)

相关问题