【问题标题】:Exclude routes with file extension from Express routes从 Express 路由中排除带有文件扩展名的路由
【发布时间】:2016-05-27 02:22:36
【问题描述】:

我希望 AngularJs 处理我的大部分路由,因此我不需要同时在 Express 和 Angular 中指定路由。所以我创建了一个这样的“包罗万象”路线:

app.use('/api', api); // server-side stuff
app.use(express.static(__dirname + '/public')); //static files
app.get('*', function (req, res) { //angular stuff
    res.render('index');
});

然后在我的 Angular 应用上,如果路由不存在,我会这样处理

$routeProvider.otherwise({
    templateUrl: '/partials/404.html', 
    controller: 'DummyCtrl'
});

问题在于,如果static() 路由与公共目录中的文件不匹配,它将转到下一个“catch all”路由。

这会导致一些问题,因为服务器返回 res.render('index');(整个页面)然后由 AngularJs 注入页面,所以我收到警告 WARNING: Tried to load angular more than once.

我想重写我的“catch all”路由,只匹配不匹配文件的路由。

我相信我需要的是 Angular 路由的正则表达式,如果它们看起来像文件,它将排除路由。例如:排除“.html”、“.png”等

【问题讨论】:

  • ^.*\.(?!(?:png|html)$).*$

标签: angularjs regex node.js express


【解决方案1】:

这里是解决方案:/\/[^.]*$|^(?:https?:)?\/\/[^\/]+$/

【讨论】:

  • 它在哪里询问寻找http
  • 无处可去。我添加了它,以便它将原始域名(例如'nationstates.net'本身)识别为'不像文件'。
猜你喜欢
  • 1970-01-01
  • 2019-06-26
  • 1970-01-01
  • 2013-04-26
  • 1970-01-01
  • 2014-04-05
  • 1970-01-01
  • 2020-02-10
  • 2019-08-11
相关资源
最近更新 更多