在Node JS中获取CSS的问题

问题描述

im尝试使用车把将CSS文件加载到Node JS应用程序中,但出现错误

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

我检查了路径及其右边。有解决办法吗?

在我的index.js中,我有app.use(express.static('public'))

和我的车把html我有<link rel='stylesheet' type="text/css" href='/styles/main.css'>

我的工作区是

-node_modules

-public
--styles
---main.css

-template-engine
--views
---layout
----main.handlebars

解决方法

这很可能是由于您调用app.use(express.static('public'))的方式引起的。通常,最好使用以下格式。

const path = require("path");
app.use(express.static(path.join(__dirname,"public")));

不幸的是,很难根据您提供的信息来猜测问题的确切原因。您可以加载其他外部资源,例如脚本或图像吗?还是只在CSS文件中遇到这种情况?这可能是因为express无法找到文件,或者您可能需要更改文件权限。此外,在stackoverflow和其他站点上至少要问这个问题数百次。您是否检查了其他questions?我确定这是否不能解决您的问题,那里的答案之一。

最后,我建议您使用express-handlebars而不是handlebars.js。它可能更适合您的需求。并且不要忘记在express-handlebars中检查默认文件结构。