繁体   English   中英

如何使用 express 读取我的 css 文件 node.js

[英]How to read my css file with express, node.js

我是快递的初学者,node.js。

我尝试构建我的应用程序,但我的 style.css 文件未被读取,我不明白为什么。

一开始,我尝试使用.scss,但是当我搜索它时,我了解到这是不可能的。

因此,我将 style.scss 转换为 style.css ,当我运行我的应用程序时,结果相同:我的样式不适用,在检查器中我收到以下消息:

localhost/:1 拒绝应用来自 'http://localhost:3000/style.css' 的样式,因为它的 MIME 类型 ('text/html') 不是受支持的样式表 MIME 类型,并且启用了严格的 MIME 检查。

当我单击链接“http://localhost:3000/style.css”时,此消息出现在选项卡中:

无法获取 /style.css

这是我的 index.js 中的代码:

const express = require('express'); 
const {engine} = require('express-handlebars');
const app = express();
const port = 3000;

app.engine('handlebars', engine({
    layoutsDir:__dirname + '/views/layouts',
}));

app.set('view engine','handlebars');
   
app.get('/', (req,res) => {
    res.render('main', {layout : 'index'})
});
app.use(express.static('public'));

app.listen(port, () => 
console.log(`Notre app est lancée sur : http://localhost:${port}`)
);

在我的 index.handlebars 中有一行:

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

在我的代码中,当我 ctrl+单击“./style.css”时,我找到了正确的 css 文件。

有人可以帮助我吗?

如果您确定style.csspublic文件夹中

index.js代码中唯一存在的问题是app.use(express.static('public')); 你在渲染页面之前添加它

例子:

const express = require('express'); 
const {engine} = require('express-handlebars');

const app = express();
const port = 3000;

app.engine('handlebars', engine({
    layoutsDir:__dirname + '/views/layouts',
}));

app.set('view engine','handlebars');

app.use(express.static('public'));
   
app.get('/', (req,res) => {
    res.render('main', {layout : 'index'});
});

app.listen(port, () => 
console.log(`Notre app est lancée sur : http://localhost:${port}`);
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM