Search code examples
jsondarthttpresponseaqueduct

Http response body has quote marks from Dart Aqueduct server


When a response is returned from an Aqueduct controller like this

return Response.ok('hello');

the body of the response has quote marks around it:

"hello"

The same thing when I return a JSON string like this:

return Response.ok('{"token":"$token"}');

I get this:

"{\"token\":\"eyJhbG...soOFY8\"}"

which is messing up the JSON parsing on the client side.

Is there any way to not send the quote marks?


Solution

  • The default ContentType of the response is JSON already. If you want to send plane text then you need to set the content type to plain text.

    // import 'dart:io';
    
    return Response.ok('hello')..contentType = ContentType.text;
    

    The response body will be

    hello
    

    To send JSON, just send a Map rather than converting it to a string yourself:

    return Response.ok({'token':token});
    

    This will give a response body of

    {"token":"eyJhbGc...vCxdE"}
    

    See also

    Credit

    Thank you to Joe Conway on the Aqueduct Slack channel for help solving this problem. I am adding the solution here as a Q&A so others can find it easier.