Learn more about Dart tutorials and technical articles.

1. Introduction

This article will introduce URL and routing in detail. In the previous several articles, some friends wrote messages saying that IT was a little fast and I felt that I couldn’t keep up with it. Therefore, in the next article, we will introduce Aqueduct related content in detail.

2. What is a URL?

Each HTTP request has a URl that can be used as an access path for the client to access the server, for example: http://xxxx.com/image/xxx.jpg, when client requests the path to the address, the server will return the corresponding image resources to the client, the URL is a Web application, the client can through the Web application to provide the URL of the operation of the Web application resources, such as: Add, delete and query data in the database, create and delete files, etc

3. The composition of the URL

URL is made up of many parts, one part is optional, https://www.baidu.com/index.html, for example, when the browser to access this URL, will display the baidu index. The HTML page, This page contains three necessary components: Scheme (HTTPS), host(www.baidu.com), and path(/index.html), where path is optional and can be multiple, and Aqueduct framework only cares about path. Access routing in Aqueduct

4. Match routes

From the code in the previous section:

1 @override 2 Controller get entryPoint {3 Call 4 router.route('/queryArticle').linkFunction((request) Async {5 Final Query = query <Article>(context); 6 final List<Article> articles=await query.fetch(); 7 return Response.ok(articles); 8 and 9}); 10 return router; 11}Copy the code

When the path accessed by the client is /queryArticle, it will match the route and obtain the content of parameters in response. ok in the code. The path can have multiple segments. Here is a bad example :/queryArticle/1, this path will not access the above resource

Variable /: ID on the routing path

In the path specification, you can have variables, most often used to get uniquely identified resources, such as: /queryArticle/1, /queryArticle/2. Typically, we use path as a variable starting with a colon, and add the following code to access the article by ID

Dart 2 @override 3 Controller get entryPoint {4 Router.route ('/queryArticle/:id').linkFunction((Request) Async {6 Final ID = request.path.variables['id']; 7 if (int.tryparse (id)! Final query = query <Article>(context) 9.. where((a) => a.id).equalTo(int.parse(id)); Final articles = await query.fetchone (); 11 If (articles! Return response. ok(articles); Else {14 return response. ok({" MSG ":"no exist"}); Else {17 return response. badRequest(body:{" MSG ":"error"}); // query failed, id is not int 18}19}); 20 return router; 21}Copy the code

Before starting the server, we insert a few pieces of data into the database






👏 is great! The program worked exactly as we thought it would

Optional path variable /[:id] or [/:id]

At present, our paths when they visit the article, we already have an access path before, now we added a, is equal to the code redundancy, this is not what we want to see, so this time, you can use the optional path, when there is id, go to visit the corresponding id, when there is no id, we will query all articles, so, Merge the previous code into the /queryArticle path and enclose the :id in brackets to indicate that this is an optional variable, as follows:

1 @Override 2 Controller get entryPoint {3 // Optional variable [:id] 4 router.route('/queryArticle/[:id]').linkFunction((request) async { 5 final id = request.path.variables['id']; 6 if(id==null){ 7 final query = Query<Article>(context); 8 final List<Article> articles = await query.fetch(); 9 return Response.ok(articles); 10 }else if (int.tryParse(id) ! = null) {11 final query = Query<Article>(context)12 .. where((a) => a.id).equalTo(int.parse(id)); 13 final articles = await query.fetchOne(); 14 if(articles! =null){15 return Response.ok(articles); 16 }else{17 return Response.ok({"msg":"no exist"}); 18 }19 }else{20 return Response.badRequest(body:{"msg":"error"}); 21}}); 23 return router; 24}Copy the code

/a/[b/[:c]] will match /a, /a/b, a/b/c, and will not match /a/c

Limit path variable /:id([0-9]+)

In general, we can use variables followed by parentheses, enclosing the regular expression /: variable (regular expression), let’s restrict the above request id to an integer, no match will return 404, and then the code judgment part can be removed

1 @override 2 Controller get entryPoint {3 // Re limit variable /: re 4 router.route('/queryArticle/[:id([0-9]+)]').linkFunction((request) async { 5 final id = request.path.variables['id']; 6 if(id==null){ 7 final query = Query<Article>(context); 8 final List<Article> articles = await query.fetch(); 9 return Response.ok(articles); 10 }else{11 final query = Query<Article>(context)12 .. where((a) => a.id).equalTo(int.parse(id)); 13 final articles = await query.fetchOne(); 14 if(articles! =null){15 return Response.ok(articles); 16 }else{17 return Response.ok({"msg":"no exist"}); 18}} 19 20}); 21 return router; 22}Copy the code

Matches all paths under the path /*

When we need to make a series of matches, we can add /* at the end of the path, such as /user/*, when the request /user/12 or /user/12/34, etc., will match, generally used in a large system of URL routing processing

The processing of 404

Our web server usually needs to do custom 404 processing, the following is the native 404 page


Aqueduct
404
API
json

1@override 2 Controller get entryPoint { 3//edit 4 final router = Router(notFoundHandler: (request) async { 5 Response response=Response.notFound(); // response.contentType= contentType.json; / / content type 7 response. Body = {" code ": 1, 'MSG' : '404'}; // contents 8 await request.respond(response); 9 logger.info("${request.todebugString ()}"); // Print log 10}); // Route object 11//edit12 return router; 13}Copy the code

Then request 404 again and you will see the corresponding content

The above is all the content of this section, if you feel that there is a harvest, you might as well click on it again, so that I can see you with me to learn the Dart server, but also a kind of affirmation of my writing 🙏!