Dart and http://pub.dartlang.org/packages/route

I started experimenting with Dart and the Route package http://pub.dartlang.org/packages/route .

Two questions immediately appeared:

1) Is it possible (and if this is what is an idiomatic way) to define a fallback route when the user points the browser to a URL that should not exist (for example, by providing a false hash fragment). In the sample code, the route structure simply raises ArgumentError("No handler found for $path") .

2) The dart editor does not serve the compiled application in the root path / , but in the path obtained from the file system directory. This allows you to check the route pattern. Is it possible for the application to be served under, say, localhost:3030/ ?

+4
source share
2 answers

1) I do not know how to do this. You can listen for each url (. *), And then manually check if $ path matches a different url, but this is messy:

  var homeUrl = new UrlPattern(r'/home'); var contactUrl = new UrlPattern(r'/contact'); var router = new Router() ..addHandler(new url.UrlPattern(r'(.*)'), matchPages) ..listen(); void matchPages(String path) { if(homeUrl.matches(path)) { // Handle home page display } else if(contactUrl.matches(path)) { // Contact page } else { // No match, handle it how you wish } } 

It would be nice to have a built-in way to pass default routes on the client.

2) Justin Fagnani (author of the Route package) indicates that you can either service your application from a separate web server (i.e. not one provided by the Dart Editor) or use a route that will also correspond to the file system path: (. * ) # the article will match the article correctly, whether the URL is localhost: 3030 / # article or C: / Dart / app / web // from / # the article. There is an open issue for Github: https://github.com/dart-lang/route/issues/31

+1
source

for point 2:
Can you do it, how to follow ?:
The variable part of the URL is given by ' window.location.pathname ';

 library urls; import 'dart:html'; import 'package:route/client.dart'; final String _pathName = window.location.pathname; final UrlPattern _base = new UrlPattern("${_pathName}"); final UrlPattern home = new UrlPattern("${_pathName}#home"); final UrlPattern page2 = new UrlPattern("${_pathName}#page2"); // useFragment: true is important! allow keep '#" un url // allow to bookmark be valid when browser is closed and reopen. final Router router = new Router(useFragment: true) // simple hack to redirect / to /#home (home UrlPattern) ..addHandler(_base, (_) => window.location.hash = "#home"); main() { router..addHandler(home, showHome) ..addHandler(page2, showPage2) ..listen(); } void showHome(String path) { query("body").children ..clear() ..add(new Element.html("<h1>Home</H1>")); } void showPage2(String path) { query("body").children ..clear() ..add(new Element.html("<h1>Page2</H1>")); } 
+2
source

Source: https://habr.com/ru/post/1479381/


All Articles