我希望我的路由匹配不以“/api/”开头的 URL
例如,“/”、“/home”、“/profile”会触发路由,但“/api/user/get”和“/api/xx”不会。
我尝试了以下正则表达式及其修改:
app.get('/^(?!api)', function(req, res) {})
最佳答案
这种路由器组织通常是用regex的in来解决的
路由匹配,而是用路由器和默认的概念
匹配。
路由器概念允许您将路线组织成符合逻辑的
单元,例如包含 API 路由的文件和包含
包含您的其他路线。
默认路由匹配尚未匹配的路由。
因此,在您的情况下,您可能有一个包含路由器的主应用程序
API 调用,其他调用的路由器,然后是默认路由
匹配其他一切。
默认路由通常用于返回 404,但您可以使用它
捕获“所有不以“/api”开头的路由,意识到没有
页面将是 404。
下面是一些工作框架代码来说明:
var express = require('express');
var app = express();
// The "non-API Router is likely to exist in a separate file
var nonAPIrouter = express.Router();
// More routes unrelated to APIs
//nonAPIRouter.get();
//////////////////////////////////////////
// The API router may be in it's own file, too.
var APIrouter = express.Router();
// Routes that start with /API
APIrouter.get('/api*', function (req, res) {
res.send('Hello API!');
});
///////////////////////////////////////
// The main app includes both routers.
app.use(APIrouter);
app.use(nonAPIrouter);
// Default route for requests not matched above
app.use(function(req, res) {
res.status(404).end('error');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
关于regex - express js路由匹配不以字符串开头的url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35003566/