Note that this blog post has been archived. Information may be out of date or incorrect.

Hard to debug, or why you should always use the right Content-Type

Today I came along a really nasty bug in a WebApp, which was caused by not setting the correct Content-Type. Took me a while to figure it out. The App had been working fine for a while now, and after writing a small extension to it, it broke down completely, because a JSON response sent from my server was suddenly invalid and could not be parsed by jQuery. The first problem was that my handler for the AJAX requests did not set a Content-Type, which somehow defaulted to text/html. The second problem was, that I had forgotten a closing tag in the HTML which was encoded inside the JSON string returned from the handler. Because the Content-Type was text/html, the browser tried to fix the missing tag by appending it to the end of the response, which obviously broke my JSON string.

From now on I will definitely always set the right Content-Type, so I never have to deal with such a bug again.