Skip to content

Commit d78a196

Browse files
authored
docs(routes): add formData (#432)
1 parent 0b23fea commit d78a196

File tree

1 file changed

+70
-1
lines changed

1 file changed

+70
-1
lines changed

docs/docs/basics/routes.md

Lines changed: 70 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -165,8 +165,77 @@ curl --request POST \
165165
The body is "Hello!".
166166
```
167167

168-
:::tip
168+
#### JSON
169+
169170
When the `Content-Type` is `application/json`, you can use `context.request.json()` to read the contents of the request body as a `Map<String, dynamic>`.
171+
172+
```dart
173+
import 'package:dart_frog/dart_frog.dart';
174+
175+
Future<Response> onRequest(RequestContext context) async {
176+
// Access the incoming request.
177+
final request = context.request;
178+
179+
// Access the request body as parsed `JSON`.
180+
final body = await request.json();
181+
182+
return Response.json(body: {'request_body': body});
183+
}
184+
```
185+
186+
We can make a request to the above handler with some data and we should see:
187+
188+
```
189+
curl --request POST \
190+
--url http://localhost:8080/example \
191+
--header 'Content-Type: application/json' \
192+
--data '{
193+
"hello": "world"
194+
}'
195+
196+
{
197+
"request_body": {
198+
"hello": "world"
199+
}
200+
}
201+
```
202+
203+
#### Form Data
204+
205+
When the `Content-Type` is `application/x-www-form-urlencoded`, you can use `context.request.formData()` to read the contents of the request body as a `Map<String, String>`.
206+
207+
```dart
208+
import 'package:dart_frog/dart_frog.dart';
209+
210+
Future<Response> onRequest(RequestContext context) async {
211+
// Access the incoming request.
212+
final request = context.request;
213+
214+
// Access the request body form data.
215+
final body = await request.formData();
216+
217+
return Response.json(body: {'request_body': body});
218+
}
219+
```
220+
221+
```
222+
curl --request POST \
223+
--url http://localhost:8080/example \
224+
--data hello=world
225+
226+
{
227+
"request_body": {
228+
"hello": "world"
229+
}
230+
}
231+
```
232+
233+
:::info
234+
The `formData` API is supported in `dart_frog >=0.3.1`
235+
:::
236+
237+
:::caution
238+
`request.formData()` will throw a `StateError` if the MIME type is not `application/x-www-form-urlencoded`.
170239
:::
171240

172241
## Responses 📤

0 commit comments

Comments
 (0)