Flask:资源被解释为样式表,但使用MIME类型text/html传输
Flask: Resource interpreted as Stylesheet but transferred with MIME type text/html
使用Blueprint的My Flask应用程序无法在Chrome和IE中显示CSS文件。
调试信息:
资源被解释为样式表,但使用MIME类型text/html/传输
我的应用程序有以下文件:
app.py
templates/index.html
static/style.css
在我的app.py
:
app = Blueprint("conf_manager",
__name__,
template_folder="templates",
static_folder="static",
static_url_path="/static")
在我的index.html
:中
<link rel="stylesheet" type="text/css" href="{{ url_for('conf_manager.static', filename='style.css') }}" />
我使用Chrome进行调试,发现浏览器可以获得文件,但类型是text/html
而不是text/css
(但JavaScript的类型还可以)。
所以我想知道为什么会发生这种情况,以及如何修复它。
我想明白了。在主应用程序中,有人添加了response.headers["Content-Type"] = 'text/html; CharSet=UTF-8'
,因此IE无法读取CSS。
我在app.py
中的代码
app = Blueprint("conf_manager",
__name__,
template_folder="templates",
static_folder="static",
static_url_path="/static")
应更改为:
app = Blueprint("conf_manager",
__name__,
template_folder="templates",
static_folder="static",
static_url_path="/conf_manager/static")
使用send_from_directory并设置mimetype:
from flask import send_from_directory
scriptPath = os.path.dirname(os.path.realpath(__file__))
os.chdir(scriptPath)
template_folder = os.path.join(os.getcwd(),'templates')
static_folder = os.path.join(os.getcwd(),'static')
app = Flask(__name__, template_folder=template_folder,static_folder=static_folder)
@app.route('/css/<path:path>')
def send_css(path):
return send_from_directory('css', path,mimetype='text/css')
这在某种程度上与Flask有关。如果您尝试在没有Flask的Web服务器的情况下直接访问HTML,那么HTML页面将加载所应用的CSS,正如预期的那样。
更具体地说,实际的解决方案是创建一个";css"文件夹中的";静态";文件夹,然后准备";css/";在代码中任何有CSS文件路径的地方。
例如
要么改变这个:
href="{{ url_for('static', filename='stylesheet.css') }}"
至
href="{{ url_for('static', filename='css/stylesheet.css') }}"
或者,更改此:
href="../static/main.css"
至
href="../static/css/main.css"
更改后,Flask将按预期加载CSS,HTML页面将在没有任何警告的情况下应用CSS。
相关文章:
- 如何通过JavaScript了解当前加载页面的mime类型或内容类型
- EventSource 的响应具有非“文本/事件流”的 MIME 类型(“文本/纯文本”)
- Node js:如何获取文件签名标头而不是 mime 类型
- 如何在 Node.js 中发送文件之前设置 MIME 类型
- 我收到消息“资源解释为脚本,但使用 MIME 类型文本/html 传输”
- 资源被解释为脚本,但使用MIME类型text/plain传输
- 找不到 IE8 MIME 类型应用程序/json
- Safari-->"应用程序缓存清单的MIME类型不正确:text/plain&”;
- 我应该对 JavaScript 源映射文件使用哪种 MIME 类型
- Internet Explorer mimeType 始终为空,并且无法在此浏览器中获取支持的 MIME 类型
- 如何在一个 Http 响应中将多个 mime 类型返回到 Web 客户端
- 如何解决“资源解释为脚本但使用 MIME 类型文本/html 传输”
- 在Codeigniter中上传ajax上的奇怪MIME类型
- Javascript:如何从HTML文件输入中获取.tgz MIME类型
- FineUploader 和 Mime 类型(------WebKitFormBoundary) 附加到文件中
- 在 Tomcat 中更改 .xml.gz 的 mime 类型
- 请求的内容类型标头包含的不仅仅是 MIME 类型,为什么
- 在该应用程序上运行SortSite时,此IMG链接到图像的MIME类型错误的文件
- $.ajax表单使用JSONP提交给Google文档:“;被解释为脚本但用MIME类型text/html传输的资源”;
- 资源被解释为图像,但使用MIME类型的应用程序/八位字节流传输