简体   繁体   English

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

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

I'm a beginner in express, node.js.我是快递的初学者,node.js。

I try to build my app but my style.css file is not read and I don't understand why.我尝试构建我的应用程序,但我的 style.css 文件未被读取,我不明白为什么。

At the beginning, I try to do with.scss but when I search about that, I've learned that it can't possible.一开始,我尝试使用.scss,但是当我搜索它时,我了解到这是不可能的。

So I transform my style.scss in style.css and it's the same result when I run my app: my style is not apply and in the inspector I've this message:因此,我将 style.scss 转换为 style.css ,当我运行我的应用程序时,结果相同:我的样式不适用,在检查器中我收到以下消息:

localhost/:1 Refused to apply style from 'http://localhost:3000/style.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. localhost/:1 拒绝应用来自 'http://localhost:3000/style.css' 的样式,因为它的 MIME 类型 ('text/html') 不是受支持的样式表 MIME 类型,并且启用了严格的 MIME 检查。

When I click on the link 'http://localhost:3000/style.css', this message appear in the tab:当我单击链接“http://localhost:3000/style.css”时,此消息出现在选项卡中:

Cannot GET /style.css无法获取 /style.css

Here my code in my index.js:这是我的 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}`)
);

In my index.handlebars I have the line in my:在我的 index.handlebars 中有一行:

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

In my code, when I ctrl+click on "./style.css", I find the right css file.在我的代码中,当我 ctrl+单击“./style.css”时,我找到了正确的 css 文件。

Someone can help me?有人可以帮助我吗?

if you are sure that style.css is in the public folder如果您确定style.csspublic文件夹中

the only problem that remains in your index.js code is app.use(express.static('public')); index.js代码中唯一存在的问题是app.use(express.static('public')); you mast add it before rendering your pages你在渲染页面之前添加它

example:例子:

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