How to serve both dynamic and static pages with Dart and shelf?

只谈情不闲聊 提交于 2019-12-03 06:53:05

You can use Cascade. It creates a chain of handlers, moving to the next one if the previous one gives a 404 or 405 response.

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}');
});
Anders

The reason is that the shelf_route methods like get must fully match the path. With static files you don't want exact matches as the remainder of the path tells you the path to the file.

For this you need to use the add method and set exactMatch: false as currently the methods like get, post etc don't expose exactMatch.

The following works

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 I've added a higher level framework called mojito that is a thin glue layer on many of the shelf components that makes this a little easier.

It's still kinda newish and poorly documented but in case you're interested you can do the following

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 calls createStaticHandler behind the scenes but also supports invoking pub serve in development mode which is very handy for stuff like polymer

A fallbackHandler can be specified for the Router. It appears that using the static handler here solves the problem.

Router routes = new Router(fallbackHandler: staticHandler)
  ..get('/item/{itemid}', handler.doItem);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!