我希望处理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`);
});

如果您try 访问URL,得到的错误(如/house/evergreen/25)是一个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 <=4.x不支持命名组,请参见this open issue(看起来是planned for v5个).

目前,您可以使用带有: prefix的命名参数,例如:

app.get(['/house/:house([a-z]+)/:street([0-9]+)'], function( req, res ) {
    res.send(`You are looking for house #${req.params.house} in ${req.params.street} street`);
});

测试:

GET /house/evergreen/25

匹配:

Express router

请参见:

Javascript相关问答推荐

为什么(1 + Number.Min_UTE)等于1?

v-textfield的规则找不到数据中声明的元素

在Phaser中查找哪个物体处于碰撞中

为什么我的includes声明需要整个字符串?

docx.js:如何在客户端使用文档修补程序

在JavaScript中声明自定义内置元素不起作用

PrivateRoute不是路由组件错误

如何在模块层面提供服务?

JS,当你点击卡片下方的绿色空间,而它是在它的背后转动时,

JS—删除对象数组中对象的子对象

NG/Express API路由处理程序停止工作

如何在箭头函数中引入or子句?

每次重新呈现时调用useState initialValue函数

输入的值的类型脚本array.排序()

将Auth0用户对象存储在nextjs类型脚本的Reaction上下文中

无法使用npm install安装react-dom、react和next

将Singleton实例设置为未定义后的Angular 变量引用持久性行为

我为什么要使用回调而不是等待?

P5play SecurityError:无法从';窗口';读取命名属性';Add';:阻止具有源的帧访问跨源帧

设置复选框根据选中状态输入选中值