javascript Express中的Express中间件(typescript)

ddrv8njm  于 2023-10-14  发布在  Java
关注(0)|答案(1)|浏览(113)

我正在将一个JavaScript应用程序的后端重写为Typescript。在auth.routes.ts中,我遇到了一个与中间件(authMiddleware)相关的错误。据我所知,这是一个输入错误,因为js扩展中的同一个文件工作正常。
请帮我弄清楚这一点。
下面是相应的代码
auth.routes.ts

import { Router } from "express"
import authMiddleware from "../middleware/auth.middleware"
import authController from "../controllers/authController"

const router = Router()

router.get("/", authMiddleware, authController.auth)

export default router

auth.middleware.ts

import "dotenv/config"
import { NextFunction, Response } from "express"
import jwt, { JwtPayload, Secret } from "jsonwebtoken"
import { CustomHeaders } from "../models"

const secretKey: Secret = process.env.secretKey as Secret

interface AuthRequest extends Request {
  user?: JwtPayload
}

function authMiddleware(req: AuthRequest, res: Response, next: NextFunction) {
  if (req.method === "OPTIONS") {
    next()
  }

  try {
    const token = (req.headers as CustomHeaders).authorization?.split(" ")[1]

    if (!token) {
      return res.status(401).json({ message: "Unauthorized" })
    }
    const decoded: JwtPayload = jwt.verify(token!, secretKey) as JwtPayload
    req.user = decoded

    next()
  } catch (error) {
    return res.status(400).json({ message: "Bad Request" })
  }
}

export default authMiddleware

错误描述:
没有重载与此调用匹配。最后一个重载给出了以下错误。类型“”的参数(请求:AuthRequest,res:Response<any,Record<string,any>>,next:NextFunction)=> Response<any,Record<string,any>>|“undefined”不能分配给类型为“RequestHandlerParams<ParamsDictionary,any,any,ParsedQs,Record<string,any>”的参数。类型“(要求:AuthRequest,res:Response<any,Record<string,any>>,next:NextFunction)=> Response<any,Record<string,any>>|未定义'不能分配给类型' RequestList <ParamsDictionary,any,any,ParsedQs,Record<string,any> String '。参数“req”和“req”的类型不兼容。类型“Request<ParamsDictionary,any,any,ParsedQs,Record<string,any>>”缺少类型“AuthRequest”中的以下属性:缓存、凭证、目的地、完整性和13个其他信息。ts(2769)
我试着询问chatGPT关于我的问题,但我也收到了非工作变量。

6qqygrtg

6qqygrtg1#

这解决了我的问题

declare global {
  namespace Express {
    interface Request {
      email: string
      password: string
      user?: JwtPayload
    }
  }
}

相关问题