expressJS:基于正则表达式的中间件

时间:2016-01-05 14:24:33

标签: javascript regex node.js express

我在expressJS 4中使用正则表达式匹配功能进行路由时遇到问题。

我想使用app.use()来定义哪些路径可用于不以/api开头的网址

routesWebAuth.js

var express = require('express');
var router = express.Router();
var webAuthenticationCtrl = require('controllers/web/auth.js');

router.post('/auth/login',   webAuthenticationCtrl.login);
router.get('/auth/isLogged', webAuthenticationCtrl.isLogged);
router.get('/auth/logout',   webAuthenticationCtrl.logout);

没有正则表达式的app.js

function routeinfo(req, res) {
  console.log("matched : " + req.path);
  next();
}
//we accept all routes
app.use('/', routeinfo, routesWebIndex);

对于请求localhost/auth/login 它返回:matched: /auth/login

带有正则表达式的app.js

function routeinfo(req, res) {
  console.log("matched : " + req.path);
  next();
}
var regex_notApi = /^\/(?!(api))/;
//only the route not starting by /api
app.use(regex_notApi, routeinfo, routesWebIndex);

对于请求localhost/auth/login,它会返回:matched: /

问题是,在我使用RegEx的情况下,路由/auth/login不匹配,因为路由器提供了网址/而不是/auth/login。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我知道为时已晚,但我认为此正则表达式可以工作:

/^\/((?!api).)*/i
app.use(/^\/((?!api).)*/i, myFunc);

此匹配//auth/auth/login/foo/foo/bar和...
而且它与/api/api//api/foo和...不匹配。
请注意,它也与/apibar/foo不匹配,我不知道这是否是您的用例。

您还可以在此处测试快速正则表达式路由:http://forbeslindesay.github.io/express-route-tester/