You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在server.ts中添加retrieveUserId时出现类型不匹配错误求助

错误原因及修复方案

核心问题:中间件参数顺序错误

Express 中间件的标准参数顺序是 (req: Request, res: Response, next: NextFunction),但你写的retrieveUserId函数把res放在了第一个参数位置,完全不符合Express中间件的类型定义,导致TypeScript识别错误,抛出'void' is not assignable to parameter of type 'PathParams'的类型不匹配报错。

修复步骤:

1. 修正中间件参数顺序

修改user-middleware-extraction.ts里的retrieveUserId函数参数顺序,同时补充无JWT时的next()调用,避免请求挂起:

export function retrieveUserId(req: Request, res: Response, next: NextFunction) {
    const jwt = req.cookies['SESSIONID']   // 获取JWT Token
    if(jwt) {
        handleSession(jwt, req)
            .then(() => next())
            .catch(err => {
                console.log(err);
                next()    
            })
    } else {
        // 无JWT时也要调用next,保证请求流程继续
        next();
    }
}

2. 修正handleSession变量顺序错误

你在handleSession里先给req['userId']赋值,但此时payload还未定义,会导致运行时错误,调整变量顺序:

async function handleSession(jwt: string, req: Request) {
    try {
        const payload = await decodeToken(jwt) // 先获取JWT payload
        req['userId'] = payload.sub // 再给request添加userId属性
    }
    catch(err) {
        console.log("error is", err)
    }
}

3. 可选:优化TypeScript类型提示(消除自定义属性报错)

因为给req添加了自定义属性userId,可以扩展Express的Request类型,避免类型检查报错:
在项目中创建types/express.d.ts文件,内容如下:

declare namespace Express {
    export interface Request {
        userId?: string; // 根据你的payload.sub实际类型调整,比如number或string
    }
}

然后在tsconfig.json中确保类型目录被识别:

{
  "compilerOptions": {
    "typeRoots": ["./node_modules/@types", "./types"]
  }
}

完成以上修改后,类型错误和潜在的运行时问题都会解决。

内容的提问来源于stack exchange,提问作者Agnum

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 04:45:57