-
Notifications
You must be signed in to change notification settings - Fork 35
Request object
A Request
object is a per-request object that encapsulates the data sent from the client. Some of the important attributes of a Request
object are:
-
uri
: The request uri/path of the request -
method
: The HTTP method of the request - Body accessor methods
-
headers
: The HTTP headers of the request -
cookies
: The cookies sent with the request -
session
: The session object of the request
The path and method of the request are exposed through uri
and method
members of the Request
object respectively.
Given the following route:
server.get('/hello', (Context ctx) {
print(ctx.req.uri);
print(ctx.req.method);
return 'Hello world!';
});
a HTTP request with path http://localhost:8080/hello?key1=value1&key2=value2
and method GET
would print:
/hello?key1=value1&key2=value2
GET
Jaguar provides simple oneliner methods to access body of the HTTP request in various useful forms.
Decoding JSON requests can't be simpler than using one of the built-in [bodyAsJson
][Doc::Request::bodyAsJson],
[bodyAsJsonMap
][Doc::Request::bodyAsJsonMap] or [bodyAsJsonList
][Doc::Request::bodyAsJsonList] methods on
[Request
][Doc::Request] object.
Future<Null> main(List<String> args) async {
final server = new Jaguar();
server.post('/api/book', (Context ctx) async {
// Decode request body as JSON Map
final Map<String, dynamic> json = await ctx.req.bodyAsJsonMap();
Book book = new Book.fromMap(json);
// Encode Map to JSON
return Response.json(book.toMap());
});
await server.serve();
}
A single line is all it takes to obtain a form as a Map<String, String>
using method [bodyAsUrlEncodedForm
][Doc::Request::bodyAsUrlEncodedForm]
on [Request
][Doc::Request] object.
main(List<String> arguments) async {
final server = new Jaguar(port: 8005);
server.post('/api/add', (ctx) async {
final Map<String, String> map = await ctx.req.bodyAsUrlEncodedForm(); // The magic!
contacts.add(Contact.create(map));
return Response.json(contacts.map((ct) => ct.toMap).toList());
});
await server.serve();
}
bodyAsFormData
method on Request
object parses and returns multipart forms as Map
<String
, FormField
>.
server.post('/upload', (ctx) async {
final Map<String, FormField> formData = await ctx.req.bodyAsFormData();
BinaryFileFormField pic = formData['pic'];
File file = new File('bin/data/' + pic.filename);
IOSink sink = file.openWrite();
await sink.addStream(pic.value);
await sink.close();
return Response.redirect(Uri.parse("/"));
});
TODO
TODO
TODO
Basics
- Route handler
- Path matching
- Path parameters
- Query parameters
- Serving static files
- Cookies
- Controller
- Parameter binding
- Hot reload
Serialization
Forms
Sessions
Authentication
- Basic authentication
- Form authentication
- JSON authentication
- Authorization
- OAuth
- MongoDb
- PostgreSQL
- MySQL
- Establish connection
- ORM
- Server sent events (SSE)
- Websockets
- systemd
- Docker
- AppEngine