快速路由:如何在静态文件上返回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')); });
任何帮助是受欢迎的。
- 卡在console.log(JSON.stringify(req))中间件
- Stormpath Express Passport保存customData或甚至默认数据
- 什么是express.json()和express.urlencoded()?
- 使用NodeJS Express和node-sass让SASS自动debugging
- 使用Express.js Node.js标头(cURL)中的令牌
- 错误:无法将用户序列化到会话中。 错误的函数传递给serializeUser()?
- Express和Cheerio / JSDOM
- mongo / node TypeError:callback不是查询中的函数
- 渲染无视图响应对象的Jade视图