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

Express 4.17 中间件传递req.app.locals变量到下游路由返回undefined问题

问题原因与解决方案

核心错误:中间件注册位置错误

Express 的 router.route() 方法仅接收路由路径作为唯一入参,你传入的第二个参数 verifyJWT 会被直接忽略,导致鉴权中间件从未执行,自然没有给 req.app.locals.userId 赋值,所以打印结果为 undefined。

修正方案

1. 调整路由中间件的注册位置

把 verifyJWT 移动到 .get() 方法的参数中,修正后的路由代码如下:

router.route("/getuser").get(verifyJWT, (req, res) => {
    console.log(req.app.locals.userId) // 此时可正常打印
});

2. 优化变量存储方式(推荐)

req.app.locals 是应用级全局共享对象,多用户并发请求时会出现变量互相覆盖的问题,建议直接把用户id挂载到当前请求的req对象上,每个请求的req实例独立,不会出现冲突:
首先修改中间件:

const verifyJWT = (req, res, next) => {
    const token = req.headers["x-access-token"]
    if (!token) {
        return res.send("We need a token") // 加return避免后续代码继续执行
    } 
    jwt.verify(JSON.parse(token), "jwtSecret", (err, decoded) => {
        if (err) {
            return res.json({ auth: false, message: "You failed to authenticate" })
        } 
        req.userId = decoded.id; // 直接挂载到req对象,仅当前请求可用
        next();
    })
}

然后在路由中直接读取:

router.route("/getuser").get(verifyJWT, (req, res) => {
    console.log(req.userId) 
});

额外注意点

所有给前端返回响应的分支都要加return,避免代码继续向下执行触发逻辑错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 01:06:04