报错摘记 | Refused to apply styleMIME-type报错CSS样式加载不出来

    xiaoxiao2025-01-05  61

    文章目录

    问题描述解决办法 补充情况解决办法 后记

    问题描述

    用Sublime Text,Browser Sync浏览器同步之后,发现样式设置没有起作用,源文件也没加载出style.css

    报错内容形如

    Refused to apply style from 'http://localhost:3000/assets/styles/custom-style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

    在Stack Overflow里找到一个类似的问题

    里面提到了url是否正确,对Node.js应用程序检查配置,是否正确引用style.css等等


    解决办法

    笔者目前遇到该问题的原因均为 路径不对,找不到对应CSS文件

    修改前

    <link rel="stylesheet" href="./style.css"> //文件结构 file |-static | |-style.css |_index.html

    修改后 根据原有文件结构,修改代码

    <link rel="stylesheet" href="./static/style.css">

    就能正常加载了

    注 ./表示当前目录,如上述代码,index.html中使用./,会找到file文件夹 ../表示父级目录,如上述代码,style.css中使用../,会找到file文件夹


    补充情况

    使用 Express, 显示 HTML 文件,报错信息如下(还是同样的配方…)

    Refused to apply style from 'http://localhost:8000/login/index.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

    相关代码

    //index.html <link rel="stylesheet" type="text/css" href="./index.css"> //app.js app.use(express.static(path.join(__dirname, '/'))); app.get('/', (req, res) => { console.log(1); res.sendFile(__dirname + '/pages/login/index.html'); }) //文件结构 demo ├─ app.js └─ pages └─ login ├─ index.css └─ index.html

    解决办法

    乍一眼是不是没觉得路径有问题,迷惑 但是这次出发点有问题,不能从 index.html文件出发来看问题,得从app.js这文件出发,因为是从它这导入的 正确写法

    <link rel="stylesheet" type="text/css" href="./pages/login/index.css">

    完事儿!


    后记

    时隔一年,又遇到了相同的报错,意外被推荐到了自己的博客 看自己写的第一篇报错记录文章,有点想吐槽(这傻逼写得什么玩意儿 屁用没有 哈哈哈哈) 故将文章补充修改了一下,希望对你有所帮助 :)

    最新回复(0)