Requests & Responses
Last updated
Last updated
Angel is inspired by Express, and such, request handlers in general represent those from Express. Request handlers can be functions, or plain Dart objects (see ). Basic request handlers accept two parameters:
- 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.
- 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, call res.end()
to prevent further writing.
Both requests and responses contain a Map of properties
that can be filled with arbitrary data and read/modified at any point during the .
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 return false
, but it will continue if you return true
.
If you return null
: Request handling will continue, unless you closed the response object by calling . Some response methods, such as or automatically close the response.
Anything else: Whatever other Dart value you return will be serialized as a response. The default method is to encode responses as JSON, and to do so using reflection (see package:json_god
). However, you can change a response's serialization method by setting res.serializer = foo;
. If you want to assign the same serializer to all responses, call on your Angel instance. If you are only returning JSON-compatible Dart objects, like Maps or Lists, you might consider injecting JSON.encode
as a serializer, to improve runtime performance.
Request handlers do not even have to be functions at all. You can provide singleton values as request handlers, and they will always be sent to clients without running any functions.
Angel automatically parses multipart/form-data
, application/json
, and application/x-www-form-urlencoded
bodies.
req.query
can be used without parsing the request body. However, the query string parser in package:body_parser
supports advanced queries like the following, so you may consider parsing the body:
For more information, see the API docs:
Request handlers can take other parameters, instead of just a RequestContext
and ResponseContext
. All parameters will be into a response, whether from , , or .
and are Map
s, and are available on each request. is a List of files uploaded to the server.
When you are in production, one way to improve performance is by only parsing request bodies when it is necessary. In such a case, you will have to use , , etc. to access request body information. The request body will only be parsed once.
If you , be sure to use the lazy
alternatives.
Now, let's learn about Angel's .