How to access Dart shelf post body parameters?

1.5k views Asked by At

I am using Dart Shelf framework for building an API. Get works fine but I am having issues with post. I couldn't access any of the body parameters of the post request in my server. Here is what I have tried.

// shelf-router
router.post('/login', (Request req) async {
  final body = await req.readAsString();
// to check
 print(body); // outputs null
 return 
 Response.ok('OK');
});

How am I testing this?

Using postman with the endpoint and body type raw (JSON).

payload as

{
  "user":"testUser",
  "password":"p455w0rd"
}

I even tried setting contenttype header to application/JSON but no luck there too.

5

There are 5 answers

0
Alex Baban On

Here is from the dart create -t server-shelf modified so it can handle a POST request on the /api/ route. Inspired by @Darshil Patel's answer.

import 'dart:io';

import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart';
import 'package:shelf_router/shelf_router.dart';

// Configure routes.
final _router = Router()
  ..get('/', _rootHandler)
  ..post('/api/', _apiHandler);

Response _rootHandler(Request req) {
  return Response.ok('Hello, World!\n');
}

Future<Response> _apiHandler(Request req) async {
  final uri = Uri(query: await req.readAsString());
  final formData = uri.queryParameters;
  print(formData);
  return Response.ok(
    '''You sent:
    $formData
    ''',
    headers: {'Content-type': 'text/plain'},
  );
}

void main(List<String> args) async {
  // Use any available host or container IP (usually `0.0.0.0`).
  final ip = InternetAddress.anyIPv4;

  // Configure a pipeline that logs requests.
  final handler = Pipeline().addMiddleware(logRequests()).addHandler(_router);

  // For running in containers, we respect the PORT environment variable.
  final port = int.parse(Platform.environment['PORT'] ?? '8080');
  final server = await serve(handler, ip, port);
  print('Server listening on port ${server.port}');
}
0
Sittiphan Sittisak On

I can receive the parameter from the postman with form-data. I am using shelf_route in the server. If this is similar to you, you can follow this: https://stackoverflow.com/a/74255231/17798537

0
Darshil Patel On

Try this inside your request handler function..

final String query = await request.readAsString();
Map queryParams = Uri(query: query).queryParameters;
print(queryParams);
1
Rubens Galvan On
final String query = await request.readAsString();
// Map<String, String> queryParams = Uri(query: query).queryParameters;
Map queryParams = jsonDecode(query);
print(queryParams['user']);
0
A J On

For the body params

var bodyString = await request.readAsString();
var body = json.decode(bodyString);

For query param

var query = request.url.queryParameters