首页 > 解决方案 > Express JS - 正则表达式 - 除了

问题描述

我正在使用 ExpressJS 4.x 开发 REST Web 服务器。我要做的是编写一个中间件来捕获所有传入的请求,除了那些以“/api/...”开头的请求

我可以使用哪个正则表达式?

//This middleware catches everything except the requests addressed to "/api/..."
app.use('<regular_expression>',express.static('public'));

//Not intercepted by the middleware
app.get("/api/foo1",function(req,res)=>{
    ......
})

//Not intercepted by the middleware
app.get("/api/foo2/bar",function(req,res)=>{
    ......
})

标签: node.jsregexexpress

解决方案


根据这个SO answer,您可以使用负面展望(它们在Javascript中可用):

app.use(/\/((?!api).)*/, app_lookup);

如您所见,正则表达式没有被引号包围。


推荐阅读