TypeError:无法读取undefined的authorization属性问题求助
问题分析与解决方案
核心问题
你写的中间件函数参数顺序搞反了。Express 中间件的标准参数顺序是 (req, res, next),但你写成了 (res, req, next),导致代码里的 req 实际上是响应对象,而真正的请求对象被当成了 res,所以 req.headers 是 undefined,进而读取 authorization 时抛出 TypeError。
修复后的代码
import jwt from "jsonwebtoken"; export const verifyToken = (req, res, next) => { const authHeader = req.headers['authorization']; const token = authHeader && authHeader.split(' ')[1]; if (token == null) return res.sendStatus(401); jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, decoded) => { if (err) return res.sendStatus(403); req.email = decoded.email; next(); }) }
额外建议
- 后续写 Express 中间件时,务必牢记参数顺序:请求对象(req)在前,响应对象(res)在后,最后是 next 函数。
- 如果后续仍遇到类似
Cannot read properties of undefined的错误,优先检查变量是否被正确赋值,尤其是函数参数的顺序和传递是否正确。
内容的提问来源于stack exchange,提问作者Ridwan Anugrah
相关产品推荐
相关产品推荐

