快速路由:如何在静态文件上返回404错误,并为angular色UI路由器维护HTML5Mode

我有一个AngularJS网页使用ui路由器在HTML5Mode路由,这意味着URL不必有“index.html#”既不是“#”。

为了达到这个目的,我将自己的expressconfiguration为ui-router wiki :

app.use('/app', express.static(__dirname + '/../web/app')); app.use('/css', express.static(__dirname + '/../web/css')); app.use('/img', express.static(__dirname + '/../web/img')); app.use('/libs', express.static(__dirname + '/../web/libs')); app.use('/views', express.static(__dirname + '/../web/views')); app.all('/*', function(req, res, next) { res.sendFile(path.resolve(__dirname + '/../web/index.html')); }); 

重要的部分是最后一行,所有调用不匹配app / css / img … return index.html

它的工作原理,问题来了,因为我有另一个规则返回公共文件:

 // Return file app.use('/file', express.static(__dirname + "/../public/", options)); 

在angular度的应用程序中,我使用$ http来获取公共文件(文件名是URL上的一个参数),如果文件存在,我使用它:

 var fileUrl = "http://mydomain/file/" + $stateParams.filename + '.png'; $http.get(fileUrl) .then( function(response){ if(response.status == 200){ // File exist } } ); 

问题是,即使文件不存在,我总是得到一个状态为200的响应。快速路由试图返回文件,但因为它不存在,它返回index.html。 这就是我想的事情

回顾:

http://mydomain/file/fileThatExist.png Returs Image http://mydomain/file/fileThatDoesNotExit.png Returs index.html

我试图使用正则expression式,但它有相同的效果

 // All calls that doesn't contain 'file' string /* ^ # Start of string (?! # Assert that it's impossible to match... file # file, followed by $ # end of string ) # End of negative lookahead assertion .* # Now match anything */ app.all(/^\/(?!file$).*/, function(req, res, next) { res.sendFile(path.resolve(__dirname + '/../web/index.html')); }); 

任何帮助是受欢迎的。