【问题标题】:Express template not linking to scripts, css, or imagesExpress 模板未链接到脚本、CSS 或图像
【发布时间】:2016-07-20 02:27:17
【问题描述】:

使用 Express,我运行 index.html 文件,但无法正确链接 css、js 或图像。没有图片显示,css和js没有链接。

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

<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/main.js"></script>

img/logo.png

我的目录结构如下:

root
    app.js
    package.json
    node_modules
    assets
        img
        css
        js
        templates
            theme1
                css
                fonts
                img
                js
                index.html
                about.html
                services.html
                news.html
                contact.html

在 app.js 中:

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

app.get('/', function(req, res) {
    //res.sendFile(path.join(__dirname + '/assets/templates/theme1/index.html'));
});

app.get('/about/', function(req, res) {
    res.sendFile(path.join(__dirname + '/assets/templates/theme1/about.html'));
});

app.get('/services/', function(req, res) {
    res.sendFile(path.join(__dirname + '/assets/templates/theme1/services.html'));
});

app.get('/services/', function(req, res) {
    res.sendFile(path.join(__dirname + '/assets/templates/theme1/news.html'));
});

app.get('/contact/', function(req, res) {
    res.sendFile(path.join(__dirname + '/assets/templates/theme1/contact.html'));
});

app.listen(3000);

需要更好地理解app.getapp.use 以及res.sendFile

谢谢大家

【问题讨论】:

    标签: javascript html css express


    【解决方案1】:

    所以,它不起作用,因为您没有告诉 Express 提供您想要的文件(js 和 css 等)。

    首先您要使用static middleware 设置静态路由:

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

    此时,“assets”目录中的所有内容都将相对于您的根 URL 提供。所以/img/someimage.jpg 是它的正确 URL。

    【讨论】:

    • 如何使用 app.use 设置 app.js 文件?我还需要 app.get 和 app.sendfile 吗?
    • 视情况而定。如果你想保持对 /about 的请求返回文件系统上 assets/templates/theme1/about.html 文件的行为,那么继续做你什么都不做的事情可能更容易,只需添加我推荐的更改在所有 app.get 声明之前。
    猜你喜欢
    • 1970-01-01
    • 2020-02-26
    • 2010-11-16
    • 1970-01-01
    • 2017-09-29
    • 2019-07-22
    • 2012-03-27
    • 2023-03-26
    • 2013-07-03
    相关资源
    最近更新 更多