3

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.

GunJack
  • 1,928
  • 2
  • 22
  • 35
  • I assume "outputs null" actually means "outputs the empty string"? (`Request.readAsString` is declared to return a `Future` that completes to a non-nullable type.) What is `router.post`? Are you sure that the `Request` hasn't already been read (per [the documentation](https://pub.dev/documentation/shelf/latest/shelf/Request/readAsString.html), it can be called only once)? Could you possibly create a minimal, reproducible example? – jamesdlin Mar 27 '22 at 11:45
  • Let me update the code – GunJack Mar 27 '22 at 12:46
  • Did you solve your problem? You never updated your question. – jamesdlin Apr 07 '22 at 05:33
  • Unfortunately no, I've given up on getting post data using shelf. I am now sending passwords, sadly, using get, encoded in the url. – GunJack Apr 08 '22 at 06:54

4 Answers4

2
final String query = await request.readAsString();
// Map<String, String> queryParams = Uri(query: query).queryParameters;
Map queryParams = jsonDecode(query);
print(queryParams['user']);
1

Try this inside your request handler function..

final String query = await request.readAsString();
Map queryParams = Uri(query: query).queryParameters;
print(queryParams);
0

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

For the body params

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

For query param

var query = request.url.queryParameters
A J
  • 191
  • 3
  • 4