如何在Django中设置JavaScript文件的内容类型 [英] How to set content type of JavaScript files in Django
问题描述
我有一个Django应用程序,它需要几个JavaScript文件.
I have a Django application, which requires several JavaScript files.
在Chrome浏览器中,我收到错误消息资源被解释为脚本,但以MIME类型text/html传输".
In Chrome I get the error "Resource interpreted as Script, but transferred with MIME type text/html".
AFAIK(请参阅 2 )为解决此问题,我需要配置Django,以便以内容类型"application/x-javascript"返回JavaScript文件.
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".
如何在Django中做到这一点?
How can I do this in Django?
更新:我遵循了Daniel Roseman的建议,并找到了解决方案.
UPDATE: I followed the advice by Daniel Roseman and found following solution.
1)修改urls.py:
1) Modify urls.py:
urlpatterns = patterns('',
...
url(r'.*\.js$', java_script),
...
)
2)在views.py中添加以下功能:
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")
推荐答案
我怀疑问题不是您想的那样.实际上可能正在发生的事情是根本没有提供您的JS文件:相反,正在发送Django错误页面.您需要找出原因.
I suspect the problem is not what you think it is. What is probably actually happening is that your JS files are not being served at all: instead, the Django error page is being sent. You need to figure out why.
这篇关于如何在Django中设置JavaScript文件的内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!