engineering perfection on rails

JSON/XML rendered as plain/text by Apache

We have a RESTful API built over Rails which exposes a certain resource in XML as well as in JSON format. The resource is read more frequently than it is updated, thus we decided to cache it using Rails' page caching feature. After deploying the application on the staging environment, the JS library consuming the API started crashing intermittently. The AJAX requests were processed successfully for uncached responses, but jQuery could not parse the cached responses.

A quick look at Firebug showed that the cached responses were rendered by Apache with a mime-type of "plain/text" rather than "application/json" as expected by jQuery.

To cut to the chase, there is a very easy way to configure apache to handle appropriate mime types for any formats. Add the following lines to /etc/apache2/mods-available/mime.conf:

AddType application/json .json
AddType application/xml .xml

Also make sure that you have enabled the mod called mime. On a Debian distro, you can execute the following command:

a2enmod mime

The change configures apache to use mime types 'application/json' or 'application/xml' while rendering any static asset with extension '.json' or '.xml' respectively.

Filed under  //   apache   caching   mime-type   rails