Express中GET路径正则含命名捕获组时崩溃,报错Cannot read property 'name' of undefined
问题描述
我想要处理GET请求并从URL中匹配相关信息,示例代码如下:
const REGEX_QUERY = /^\/?house\/(?<street>[a-z]+)\/(?<house>[0-9]+)$/i; const REGEX_QUERY_NO_NAMES = /^\/house\/([a-z]+)\/([0-9]+)$/i; app.get([REGEX_QUERY], async (req, res, next)=>{ res.setHeader("Content-Type", "text/plain"); const match = REGEX_QUERY.exec(req.path); res.send(`You are looking for house #${match.groups.house} in ${match.groups.street} street`); });
当访问类似/house/evergreen/25这样的URL时,会触发500错误,且该错误在路径处理器运行前就已发生,完整堆栈信息如下:
TypeError: Cannot read property 'name' of undefined at Layer.match (/MY_EXPRESS_PROJECT/node_modules/express/lib/router/layer.js:147:20) at matchLayer (/MY_EXPRESS_PROJECT/node_modules/express/lib/router/index.js:585:18) at next (/MY_EXPRESS_PROJECT/node_modules/express/lib/router/index.js:226:15) at SendStream.error (/MY_EXPRESS_PROJECT/node_modules/serve-static/index.js:121:7) at SendStream.emit (events.js:400:28) at SendStream.error (/MY_EXPRESS_PROJECT/node_modules/send/index.js:270:17) at SendStream.onStatError (/MY_EXPRESS_PROJECT/node_modules/send/index.js:417:12) at next (/MY_EXPRESS_PROJECT/node_modules/send/index.js:731:16) at onstat (/MY_EXPRESS_PROJECT/node_modules/send/index.js:720:14) at FSReqCallback.oncomplete (fs.js:192:21)
若移除命名捕获组,改用.get([REGEX_QUERY_NO_NAMES] ...,剩余代码可正常运行,返回内容如下:
You are looking for house #25 in evergreen street
问题原因
这个错误是由于你使用的Express版本不支持正则命名捕获组导致的。
从堆栈信息可以看到,错误发生在Express的Layer.match方法中,旧版本Express的路由匹配逻辑没有兼容正则命名捕获组的结构,在处理这类正则时会尝试访问一个未定义对象的name属性,从而抛出TypeError异常。
而普通无命名的捕获组是Express旧版本能够正常识别的正则语法,所以改用这类正则后,路由匹配逻辑可以正常执行,不会触发错误。
你可以通过升级到支持正则命名捕获组的Express新版本,或者继续使用普通捕获组的方式来解决这个问题。
内容的提问来源于stack exchange,提问作者Tomáš Zato
相关产品推荐
相关产品推荐

