[dancer-users] Incorrect attempts to serialize HTML

Andrew Beverley andy at andybev.com
Sun Oct 12 15:33:22 BST 2014


On Thu, 2014-10-09 at 19:43 +0200, Sawyer X wrote:
> Not at all! That is an excellent question.

Great, thanks for the prompt reply.

> You can see that Dancer2::Core::Request checks for a supported content
> type. The line is:
> 
> 
>     return unless
> $self->serializer->support_content_type($content_type);
>
> However, in Dancer2::Core::Response, it doesn't check for a supported
> content type in the request in order to serialize a response back.
> This would be the correct behavior since a serializer basically says
> "I would like to serialize my responses" and not "I would like to
> serialize my responses IF the request was made with a header". The
> reason it ignores any request header in the response is because it is,
> by definition, a *request* header. This means it only relates to the
> request, not the response.

Right, got it. Thanks. Basically, when I was receiving requests for JSON
from the browser, I was forwarding to a normal HTML page in the case of
an exception. This was causing the problems with the HTML being
serialized.

> If you would like to return HTML and serialized information, you have
> two options:
> 1. Separate the code that accepts and returns serialized data into two
> different Dancer2 apps.
> 2. Don't use a serializer, and call the to_json and from_json when
> *you* decide it's the right time for it.

What I've done is to detect whether the request is for serialized data,
and if it is then not to forward the HTML page in the case of an
exception.

One thing I did find is that request->content_type was empty when I
called it (in the controller after an exception). So instead, I used

    if (request->serializer =~ /JSON/)

That seems a bit messy. Is there a better way?

Thanks again,

Andy





More information about the dancer-users mailing list