Express JS 中间件中使用的正则表达式不传递 url 参数



我在位于该文件中的中间件中使用以下regex:

//notebook/w+/(?!delete|save|entry)w+/

就我所测试的而言,regex按预期工作(下面的演示是从控制台复制的(:

//notebook/w+/(?!delete|save|entry)w+/.test("/notebook/5e5f8bcf0f3ec87973a7e2a5/5e5f8bcf0f3ec87973a7e2a6?id=5e5f8bcf0f3ec87973a7e2a4")
true

然而,端点的参数不会传递到中间件中:

console.log app/routes/notebook.ts:71
Params: {} Original URL: /notebook/5e5f8f85562da17d3088ddaa/5e5f8f85562da17d3088ddab?id=5e5f8f85562da17d3088dda9
● Notebook entry can be accessed
Failed: Object {
"detail": "Regex matched path for /notebook/:notebookId/:entryId, but the entry id undefined cannot be found",
"status": 500,
"title": "Serverside error",
"type": "generic-001",
}
319 | 
320 |                 if (res.status !== 200) {
> 321 |                   fail(res.body);
|                   ^
322 |                 }
323 | 
324 |                 expect(res.status).toBe(200);

321线

我认为这是因为express没有将请求的端点与中间件相关联,但我不确定它是如何不关联的,因为中间件是根据请求执行的,而且我可以在中获取所有其他变量,例如url的查询部分中的id和originalUrl,而不是url的参数。

我该如何补救?

Express基于:表示法从url中提取params对象。因此,如果您的正则表达式实际上没有表示法,它将不会提取这些模式并将其作为对象。它会找到中间件,但不会解析对象。

试试//notebook/:notebookid/:entryid?w+/(?!delete|save|entry)w+/之类的东西。

此外,我认为您的代码可能会对不使用entryid的URL感到有点困惑,比如/notebook/:notebookId(第163行(。

最新更新