【问题标题】:How to make jade loading the css file? (It doesn't work)如何让jade加载css文件? (它不起作用)
【发布时间】:2020-11-12 19:24:00
【问题描述】:

这是我的目录

enter image description here

newTab.jade 代码

doctype html
html
    head
        title New Tab
        link(rel = 'stylesheet', type = 'text/css', href = '/public/index.css')
    body
        p hello world

index.css 代码

p{
    background-color: black;
    color: white;
}

app.js 代码

const express = require('express');
const app = express();
const port = 3000;
app.locals.pretty = true;
app.listen(port, function(){
    console.log("Server Connected port: "+port);
});

app.set('view engine', 'jade');
app.set('views', './views');

app.get('/', function(req, res){
    res.render('newTab');
});

jade 文件无法加载 css 文件。 我试过了 href = "/public/index.css" 但它也不起作用。

【问题讨论】:

  • 检查网络标签。你能观察到对 CSS 文件的请求吗?
  • 我不明白“网络标签”的含义
  • 我上传的代码就是我的代码。
  • 在浏览器的开发人员工具中 (F12),有一个网络选项卡记录页面发出的请求。打开该选项卡,然后刷新页面,看看您的页面发出了什么样的请求。
  • 该错误通常意味着找不到css文件。您的快速配置不包括任何静态文件配置。更多信息请参考this

标签: javascript html css express pug


【解决方案1】:

将中间件附加到 Express 以提供静态文件。

在您的 app.js 文件中:

// require path module to join your public folder with __dirname
const path = require('path');

//...

app.get('/', function(req, res){
    res.render('newTab');
});

app.use('/', express.static(path.join(__dirname, 'public')));

express.static可以做更多的事情。例如。设置maxAge 用于缓存目的:

// 31557600000ms = 1 year
app.use('/', express.static(path.join(__dirname, 'public'), { maxAge: 31557600000 }));

【讨论】:

  • 这是解决方案:)
【解决方案2】:

建议

试试

doctype html
html
    head
        title New Tab
         include index.css
    body
        p hello world

在你的 newTab.jade 文件上

并在视图目录中包含 index.css

【讨论】:

  • app.set('views', './views'); on app.js 意味着包含视图文件在视图目录中
  • 在 newTab.jade 文件中丢弃 link(rel = 'stylesheet', type = 'text/css', href = '/public/index.css')
  • "include" 标签刚刚加载 "text" // p{backgroud.... } 在页面返回
  • @SeungUnOh 缩进几个空格
  • @SeungUnOh 标题下面应该有空格
猜你喜欢
  • 1970-01-01
  • 2021-11-05
  • 1970-01-01
  • 2020-09-25
  • 1970-01-01
  • 1970-01-01
  • 2018-06-25
  • 1970-01-01
相关资源
最近更新 更多