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

Express.js正则表达式路由匹配报错问题求助

Express.js正则表达式路由匹配报错问题求助

嘿,我看你在尝试匹配/old-page和old-page.html这两个路径时遇到了路由解析的错误,咱们来一起搞定这个问题~

首先先还原一下你的代码和遇到的错误:

你的代码

const express = require('express')
const app = express()
const path = require('path')
const PORT = process.env.PORT || 3000

app.get('/old-page(.html)?',(req,res)=>{
  res.send("hi");
})

app.listen(PORT,(req,res)=>{
  console.log(`The server is running in the port ${PORT}`);
})

报错信息

C:\Express JS\node_modules\path-to-regexp\dist\index.js:123
throw new TypeError(Unexpected ${nextType} at ${index}, expected ${type}: ${DEBUG_URL});
^
TypeError: Unexpected ( at 9, expected END: https://git.new/pathToRegexpError
at Iter.consume (C:\Express JS\node_modules\path-to-regexp\dist\index.js:123:15)
at consume (C:\Express JS\node_modules\path-to-regexp\dist\index.js:179:16)
at parse (C:\Express JS\node_modules\path-to-regexp\dist\index.js:183:20)
at C:\Express JS\node_modules\path-to-regexp\dist\index.js:294:74
at Array.map ()
at pathToRegexp (C:\Express JS\node_modules\path-to-regexp\dist\index.js:294:25)
at Object.match (C:\Express JS\node_modules\path-to-regexp\dist\index.js:264:30)
at matcher (C:\Express JS\node_modules\router\lib\layer.js:86:23)
at new Layer (C:\Express JS\node_modules\router\lib\layer.js:93:62)
at Function.route (C:\Express JS\node_modules\router\index.js:428:17)
Node.js v22.14.0

问题原因

这个错误是因为Express底层依赖的path-to-regexp库不识别你写的/old-page(.html)?这种字符串路径写法。在它的语法规则里,括号()默认是用来定义捕获路由参数的,而非原生正则里的分组匹配;同时你写的.html里的点.没有转义,会被当成任意字符匹配,进一步触发了语法解析错误。

解决方案

这里有两种靠谱的写法可以实现你的需求:

方案1:直接使用正则表达式字面量

把路由路径换成标准的正则表达式,path-to-regexp会直接按照正则规则解析:

const express = require('express')
const app = express()
const path = require('path')
const PORT = process.env.PORT || 3000

// 正则匹配/old-page和/old-page.html
app.get(/^\/old-page(\.html)?$/, (req,res)=>{
  res.send("hi");
})

app.listen(PORT,()=>{
  console.log(`The server is running in the port ${PORT}`);
})

这个正则的逻辑很清晰:

  • ^ 匹配路径开头
  • \/old-page 精准匹配/old-page
  • (\.html)? 可选匹配.html(?表示前面的分组可以出现0次或1次)
  • $ 匹配路径结尾

方案2:使用path-to-regexp支持的字符串语法

如果不想用正则字面量,可以用它支持的非捕获分组语法(?:开头),同时注意转义点.(字符串里要写两个反斜杠\\):

const express = require('express')
const app = express()
const path = require('path')
const PORT = process.env.PORT || 3000

// 用path-to-regexp支持的语法实现可选匹配
app.get('/old-page(?:\\.html)?', (req,res)=>{
  res.send("hi");
})

app.listen(PORT,()=>{
  console.log(`The server is running in the port ${PORT}`);
})

这里的(?:\\.html)?表示非捕获的可选分组,既不会把.html作为路由参数捕获,又能实现你要的可选匹配效果。

两种方案都能正确匹配/old-page和/old-page.html,你可以根据自己的习惯选择~

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.08 11:33:08