DartVM服务器开发(第十一天)--Jaguar处理请求
2018-08-31 本文已影响52人
rhyme_lph
我们昨天学会了如何搭建jaguar这个框架,并且成功的返回了一个html页面,可以知道,Jaguar框架真的是十分的方便好用,如果大家都感觉好用可以多多到Jaguar给一个大大的star,好了,今天我们来学习一下Jaguar处理请求
1.方法请求
通过new 一个Jaguar对象,然后调用它封装好的方法处理请求,然后调用.serve()方法开启服务器
main()=>new Jaguar()
..get('/api/doGet', (ctx) =>'Hello')
..getJson('/api/doGetJson', (ctx)=>'{"id":3221}')
..post('/api/doPost', (ctx) =>ctx.bodyAsJson())
..postJson('/api/doPostJson', (ctx)=>'{"id":4234}')
..delete('/api/doDelete', (ctx)=>'delete')
..deleteJson('/api/doDelete', (ctx) =>'{"id":253}')
..put('/api/doPut', (ctx)=>'put')
..putJson('/api/doPutJson', (ctx)=>'{"id":2343}')
..options('/api/doOptions', (ctx)=>'options')
..patch('/api/doPatch', (ctx)=>'Patch')
..html('api/doHtml', (ctx)=>'''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
Body
</body>
</html>''')
..json('/api/doJson', (ctx)=>'{"id":123}')
..serve(logRequests: true);
上面就是Jaguar处理请求的所有方法,我们来分析一下这些方法吧!
- get/post/delete/put/options/patch
- method=get/post/delete/put/options/patch
- getJson/postJson/deleteJson/putJson
- method=get/post/delete/put
- headers.mimeType=MimeTypes.json 即应答头类型为
application/json
- html
- method=get
- headers.mimeType = MimeTypes.html 即应答头类型为
text/html
- json
- method=get/post/pub/delete
- headers.mimeType=MimeTypes.json 即应答头类型为
application/json
OK 上面就是解释这些方法的接收请求方法跟返回的应答头
2.处理请求参数分析
我们再来分析一下一个方法里面的所有参数吧!
get(String path, RouteHandler handler,
{Map<String, String> pathRegEx,
ResponseProcessor responseProcessor,
List<RouteInterceptor> after,
List<RouteInterceptor> before,
List<ExceptionHandler> onException})
类型 | 参数 | 介绍 |
---|---|---|
String | path | 请求的相对地址 |
RouteHandle | handle | 路由处理使用为(ctx){}这里含有一个Context(ctx)参数 |
Map<String, String> | pathRegEx | 请求路径上使用正则例如:path:/:value/hello pathRegEx: {'value':r'^[0-9]*$'} 那么value必须是一个数字,否则不接收该请求 |
ResponseProcessor | responseProcessor | 应答处理,含有一个Response<dynamic> 类型的参数 |
List<RouteInterceptor> | before | 拦截器列表,在处理请求之前拦截 |
List<RouteInterceptor> | after | 拦截器列表,在处理请求之后拦截 |
List<ExceptionHandler> | onException | 异常处理列表,在请求发生异常时处理 |
使用:
..get('/api/doGet/:ls', (ctx) => 'Hello', pathRegEx: {
'ls': r'^[0-9]*$'
}, responseProcessor: (process){
print(process.statusCode);
},before: <RouteInterceptor>[
(ctx) {
print('before:${ctx.path}');
}
], after: <RouteInterceptor>[
(ctx) {
print('after:${ctx.path}');
}
], onException: <ExceptionHandler>[
(ctx, error, stack) {
print('异常信息:$error,堆栈:$stack');
}
])
我们来请求一次吧:

可以看到,我没有出现异常,按照正常的来走,先运行before后是responseProcessor,最后是after
那么我们制造一个异常看看有没有捕获到


可以看到,我们的异常已经被捕获了,服务器也没有挂掉,上面的异常页面是默认的,可以看到哪里出错了
3.自定义异常
当异常发生时,如果你要自己定义异常,我们可以继承一个ErrorWriter抽象类,实现404页面跟500页面的自定义
class RhymeErrorWrite extends ErrorWriter{
@override
FutureOr<void> make404(Context ctx) {
//找不到页面时返回
final resp =
Response('''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
404
</body>
</html>''', statusCode: HttpStatus.notFound);
resp.headers.contentType = ContentType.html;
ctx.response = resp;
}
@override
FutureOr<void> make500(Context ctx, Object error, [StackTrace stack]) {
// 服务器出错返回
final resp =
Response('''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
500
</body>
</html>''', statusCode: HttpStatus.internalServerError);
resp.headers.contentType = ContentType.html;
ctx.response = resp;
}
}
在这里也可以将异常信息写入到日志中,当然了,这个自定义肯定是满足不了大部分需求的,如果要查看更多可以看一下DefaultErrorWriter这个类
我们现在将这个自定义设置到服务器那里吧!
main() => new Jaguar(
errorWriter: new RhymeErrorWrite(),
)
..get('/api/doGet/:ls', (ctx){
throw new Exception('发生异常');
})
//....
然后请求一下刚才出异常的页面


可以看到,出现我自定义的页面了!
ok,今天就到这里了,我们明天见吧!
如果想继续学习DartVM服务器开发,请关注我,学习更多骚操作!