【问题标题】:Static files with Express使用 Express 的静态文件
【发布时间】:2016-08-28 00:25:42
【问题描述】:

我正在尝试在翡翠模板中链接样式表,并得到 404。我有样式表的确切路径,并且我的应用程序配置为从我的“静态”目录提供静态文件,但我是仍然得到 404 吗?另外为什么需要提供静态文件?为什么不能在您的模板中链接到它们?

'use strict';

var express = require('express');
var app = express();

app.set('view engine', 'jade')
app.set('views', __dirname + '/templates')

app.listen('3000', function(){
    console.log('Running on port 3000');
})

app.use(express.static(__dirname + '/static'));

// Routes

app.get('/', function(request, response){
    response.render('index')    
});

app.get('/blog:id', function(request, response){
    response.send('This is the blog page.')
})

app.get('/about', function(request, response){
    response.send('This is the about page.')
})

翡翠模板

html
    head
        link(rel="stylesheet", href="../../static/css/normalize.css")
        link(rel="stylesheet", href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css", integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7", crossorigin="anonymous")
        link(rel="stylesheet", href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css", integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r", crossorigin="anonymous")
    body
        div.hero(style="width: 100%; height: 400px; background-color: blue")
            h1(style="color: white;") This is the landing page !
        script(src="https://code.jquery.com/jquery-2.2.3.min.js",   integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo=",   crossorigin="anonymous")
        script(src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js", integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS", crossorigin="anonymous")

【问题讨论】:

    标签: css express static pug stylesheet


    【解决方案1】:

    你可以让你的css文件url相对于静态文件夹

    link(rel="stylesheet", href="/css/normalize.css")
    

    【讨论】:

    • 对不起,我的错。它应该在链接前面有一个反斜杠。你试过吗?
    • 是的,我只是没有运气。
    • 当您使用 express.static() 时,是否只允许您使用静态文件相对于静态文件夹的文件路径从项目中的任何位置引用静态文件?
    • 是的,您设置引用的方式应该与静态文件夹相关。请参阅此处的第一个示例:expressjs.com/en/starter/static-files.html
    • 我知道的是,如果你使用express.static('xxx', __dirname + '/static'),你可以通过'http://host/xxx/file'访问文件'/static/file'。由于前面没有'xxx',您可以通过'http://host/file' 访问该文件。希望你能明白我想要表达的意思
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 2014-02-23
    • 1970-01-01
    相关资源
    最近更新 更多