Requests & Responses
Requests and Responses
Angel is inspired by Express, and such, request handlers in general resemble those from Express. Request handlers can return any Dart object (see how they are handled). Basic request handlers accept two parameters:
RequestContext
- Contains vital information about the client requesting a resource, such as request method, request body, IP address, etc. The request object can also be used to pass information from one handler to the next.ResponseContext
- Allows you to send headers, write data, and more, to be sent to the client. To prevent a response from being modified by future handlers, callres.end()
to prevent further writing.
Return Values
Request handlers can return any Dart value. Return values are handled as follows:
If you return a
bool
: Request handling will end prematurely if you returnfalse
, but it will continue if you returntrue
.If you return
null
: Request handling will continue, unless you closed the response object by callingres.close()
. Some response methods, such asres.redirect()
orres.serialize()
automatically close the response.A
RequestHandler
: the returned handler will be executed.A
Stream
:toList
will be called, and then returned.A
Future
: it will be awaited, and then returned.Anything else: Whatever other Dart value you return will be serialized as a response. The default method is to encode responses as JSON, using
json.encode
. However, you can change a response's serialization method by settingres.serializer = foo;
. If you want to assign the same serializer to all responses, globally setserializer
on your Angel instance. If you are only returning JSON-compatible Dart objects, like Maps or Lists, you might consider injectingJSON.encode
as a serializer, to improve runtime performance (this is the default in2.0
).
Other Parameters
Request handlers can take other parameters, instead of just a RequestContext
and ResponseContext
. Consult the dependency injection documentation.
Queries, Files and Bodies
You can access a mutable Map
based on the URI query parameters by calling RequestContext.queryParameters
.
Consult the body parsing documentation to understand how to handle user input.
If you write your own plugin, be sure to use the lazy
alternatives.
For more information, see the API docs:
Next Up...
Now, let's learn about Angel's flexible router.
Last updated