How to set content type of JavaScript files in Django

Viewed 11826

I have a Django application, which requires several JavaScript files.

In Chrome I get the error "Resource interpreted as Script, but transferred with MIME type text/html".

enter image description here

AFAIK (see 2) in order to fix this problem, I need to configure Django so that JavaScript files are returned with content-type "application/x-javascript".

How can I do this in Django?

UPDATE: I followed the advice by Daniel Roseman and found following solution.

1) Modify urls.py:

urlpatterns = patterns('',
    ...
    url(r'.*\.js$', java_script),
    ...
)

2) Add following function to views.py:

def java_script(request):
    filename = request.path.strip("/")
    data = open(filename, "rb").read()
    return HttpResponse(data, mimetype="application/x-javascript")
7 Answers

I had an issue with Django serving javascript files as text/plain with the included server, which doesn't work too well with ES6 modules. I found out here that you could change file extension associations by placing the following lines in your settings.py:

#settings.py
if DEBUG:
    import mimetypes
    mimetypes.add_type("application/javascript", ".js", True)

and javascript files were now served as application/javascript.

Expanding on Alexandre's answer using put the below code into settings.py of your main project. After that you will need to clear your browser cache (you can test it by opening an incognito window as well) in order to get the debug panel to appear.

if DEBUG:
    import mimetypes
    mimetypes.add_type("application/javascript", ".js", True)

I ran into that error today even after adding @piephai s solution to my settings.py. I then noticed that @Daniel Roseman got it right as well: My import paths were wrong, I had to add ".js" to all of them, for example:

import {HttpTool} from "./requests"; became import {HttpTool} from "./requests.js";

Makes sense after thinking about how routes for static files are generated.

The solution to the problem is describe in the documentation

  • For Windows, you need to edit the registry. Set HKEY_CLASSES_ROOT\.js\Content Type to text/javascript.
Related