小编典典

CSS文件被阻止:MIME类型不匹配(X-Content-Type-Options:nosniff)

node.js

我正在开发Angular 4应用,我想应用一些全局样式。在有关角度站点教程之后,我在应用程序的根目录中创建了一个“
styles.css”文件,并在我的应用程序的index.html中引用了该样式表:

<link rel="stylesheet" type="text/css" href="styles.css">

angular应用已成功编译:

$ ng serve 
** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200 **
[...]
webpack: Compiled successfully.

但是,当我在Chromium浏览器中访问http://
localhost:4200
时,控制台显示错误消息

GET http://localhost:4200/styles.css

在Firefox浏览器中,该错误更为明显:

GET 
http://localhost:4200/styles.css [HTTP/1.1 404 Not Found 15ms]
The resource from "http://localhost:4200/styles.css" was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).

这两个文件index.html和styles.css都位于我的角度应用程序的根目录中。我试图获得有关该问题的更多信息

nosniff
    Blocks a request if the requested type is

        "style" and the MIME type is not "text/css", or
        "script" and the MIME type is not a JavaScript MIME type.

但是我不明白为什么它使请求无效,因为我type="text/css"在引用样式表时已指定。


阅读 1670

收藏
2020-07-07

共1个答案

小编典典

我只是遇到了同样的问题。它似乎是Express的一个怪癖,它可以出于几种不同的原因而表现出来,这是根据在网络上搜索“
nodejs express css mime类型”的点击次数来判断的。

尽管type="text/css"我们在<link元素中添加了属性,但Express仍将CSS文件返回为

Content-Type: "text/html; charset=utf-8"

而实际上应该将其返回为

Content-Type: "text/css"

对我来说,快速而肮脏的解决方法是简单地删除rel=属性,即更改

<link rel="stylesheet" type="text/css" href="styles.css">

<link type="text/css" href="styles.css">

测试确认CSS文件已下载且样式确实有效,并且就我的目的而言已经足够了。

2020-07-07