2012-01-28 28 views
1

我開始使用flatiron作爲Web應用程序的工具集來設置事物。Flatiron js - 導演 - 如何從表中進行異步路由?

我使用app.plugins.http導演,似乎無法弄清楚如何爲靜態文件創建「catchall」路線& 404s - 看來.get("<RegEx>")只與第一個文件夾位置匹配,所以如果<RegEx>/.*,它將匹配/foo,但不匹配/foo/bar

這裏是我的代碼,一個更好的例子:

routes.js

var routes = { 
    /* home 
    * This is the main route, hit by queries to "/" 
    */ 
    "/" : { 
    get: function(){ 
     getStatic("html/index.html",_.bind(function(err,content){ 
     if(err) throw err; 
     renderContent(this,content); 
     },this)); 
    } 
    }, 
    /* static files 
    * Last rule, if no other routes are hit, it's either a static resource 
    * or a 404. Check for the file then return 404 if it doesn't exist. 
    */ 
    '/(.*)' : { 
    get : function(){ 
     getStatic(this.req.url,_.bind(function(err,content){ 
     if(!err){ 
      renderContent(this,content); 
     } else { 
      this.res.writeHead(404); 
      // TODO: fancier 404 page (blank currently) 
      this.res.end(); 
     } 
     },this)) 
    } 
    } 
} 

,並在我的主要的應用程序文件:

/* Define the routes this app will respond to. */ 
var routes = require('./lib/routes'); 
/* set up app to use the flatiron http plugin */ 
app.use(flatiron.plugins.http); 
/* loop through routes and add ad-hoc routes for each one */ 
for(var r in routes){ 
    var route = routes[r]; 
    if(!routes.hasOwnProperty(r)) continue; 
    for(var method in route){ 
     if(!route.hasOwnProperty(method)) continue; 
     app.router[method](r,route[method]); 
    } 
} 
/* Start the server */ 
app.listen(8080); 

我希望能夠保持我的路線在一個單獨的模塊中,並導入它們 - 我很不清楚這種方法或使用導演和香草http服務器會更好,但我已經嘗試了兩種方式,沒有任何運氣。

這裏就是我得到:

localhost:8080/ 
>> (content of index file - this works) 
localhost:8080/foo 
>> (blank page, 404 header) 
localhost:8080/foo/bar 
>> (no static file for this - I get a 404 header, but the body is now "undefined" - where is this coming from??) 
localhost:8080/css/min.css 
>> (this file should exist, but the route is never called. I do however still get a 404 header, and get the "undefined" body) 

所以,我假設了「不確定」身體是不確定的路由默認行爲。

有沒有辦法在不爲每個深度添加規則的情況下創建一個catchall路線?

回答

2

嘗試使用的onError:

app.use(flatiron.plugins.http,{ 
    onError: function (err) { 
     this.res.end('Nope'); 
    } 
}); 

要管理你的靜態文件,我建議你用熨斗/工會+ connect.static