2014-12-06 15 views
8

使用shelf_static擔任過飛鏢靜態網頁是沒有問題的:如何使用Dart和書架同時提供動態頁面和靜態頁面?

var staticHandler = createStaticHandler(staticPath, defaultDocument:'home.html'); 
io.serve(staticHandler, 'localhost', port).then((server) { 
    print('Serving at http://${server.address.host}:${server.port}'); 
}); 

,我可以使用動態網頁shelf_route罰款:

Router routes = new Router() 
    ..get('/item/{itemid}', handler.doItem); 
var handler = const shelf.Pipeline() 
    .addHandler(routes.handler); 

io.serve(handler, 'localhost', port).then((server) { 
    print('Serving at http://${server.address.host}:${server.port}'); 
}); 

但我用添加掙扎靜態處理程序的動態版本。 事情我已經嘗試過包括:

Router routes = new Router() 
    ..get('/item/{itemid}', handler.doItem) 
    ..get('/', staticHandler); 

或...

..get('/.*', staticHandler); 

或...

..get('/{any}', staticHandler); 

所有這一切給我指定的默認home.html頁面,如果我要求​​但明確要求現有網頁http://localhost:8080/home.html給我沒有找到。

我是否應該嘗試使用shelf_static來做到這一點?如果不是,那麼正確的方法是什麼? 謝謝!

回答

9

您可以使用Cascade。它創建了一系列處理程序,如果前一個程序給出404或405響應,則會移至下一個處理程序。

var staticHandler = createStaticHandler(staticPath, defaultDocument:'home.html'); 
var routes = new Router() 
    ..get('/item/{itemid}', handleItem); 

var handler = new Cascade() 
    .add(staticHandler) 
    .add(routes.hander) 
    .handler; 
io.serve(handler, 'localhost', port).then((server) { 
    print('Serving at http://${server.address.host}:${server.port}'); 
}); 
+0

啊 - 這不僅僅是回退處理程序。優秀。 – th65 2014-12-06 20:56:15

2

A fallbackHandler可以指定爲Router。看來在這裏使用靜態處理程序解決了這個問題。

Router routes = new Router(fallbackHandler: staticHandler) 
    ..get('/item/{itemid}', handler.doItem); 
6

的原因是shelf_route方法,如get必須充分匹配的路徑。使用靜態文件時,您不需要完全匹配,因爲路徑的其餘部分會告訴您文件的路徑。

爲此,您需要使用add方法,並設置exactMatch: false作爲目前的方法,如getpost等不暴露exactMatch

以下工作

void main(List<String> args) { 

    Logger.root.onRecord.listen(print); 

    var staticHandler = createStaticHandler('../static', defaultDocument:'home.html'); 

    final root = router() 
    ..get('/item/{itemid}', (Request request) => 'handling the item') 
    ..add('/', ['GET'], staticHandler, exactMatch: false); 

    printRoutes(root); 

    io.serve(root.handler, InternetAddress.ANY_IP_V6, 9999); 

} 

FYI我也添加了mojito更高層次的框架,是許多現成的組件中,使得這一點更容易薄膠層。

它仍然有點新望和不良記錄,但如果你有興趣,你可以做以下

void main(List<String> args) { 

    Logger.root.onRecord.listen(print); 

    final app = mojito.init(); 

    app.router 
    ..get('/item/{itemid}', (String itemid) => 'handling the item $itemid') 
    ..addStaticAssetHandler('/', fileSystemPath: '../static', 
     defaultDocument:'home.html'); 

    app.start(); 
} 

addStaticAssetHandler電話createStaticHandler在幕後,但也支持調用的酒吧服務於發展方式這是非常方便東西像聚合物