javascript - express.static 仅加载到 index.html

标签 javascript html node.js

我正在尝试获取公用文件夹中的静态文件(图像、js、css)以供我的所有路由使用。我只能将它们加载到 index.html。 management.html 文件无法访问静态文件,我在 Chrome 控制台上收到 404 错误。

文件夹结构:

-app/  
---index.html
---management.html
---public/
------css/
------js/
------img/

服务器.js:

const express = require('express');
const path = require('path');

var app = express();

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

app.get('/', function(req, res) {
    res.sendFile('index.html', {root: __dirname })
});

app.get('/management', function(req, res) {
    res.sendFile('management.html', {root: __dirname })
});

app.listen(3000);

最佳答案

在您的 HTML 文件中,您可能指的是静态文件的相对路径。例如:<img src="img/example.png"> .此链接将基于您当前的位置。

当你的当前位置是http://example.com/ (index.html),那么它将引用http://example.com/img/example.png ,文件可能所在的位置。

但是当你的位置是http://example.com/management (management.html),它指的是http://example.com/management/img/example.png ,这将返回 404。

使用这个文件的绝对路径就可以解决这个问题。您可以通过放置一个 / 来做到这一点相对路径前面:<img src="/img/example.png"> .或者,您可以在 management.html 中使用相对路径像这样:<img src="../img/example.png"> .

关于javascript - express.static 仅加载到 index.html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44344964/

相关文章:

node.js - 从上一个意图中获取后续意图中的参数

javascript - 自定义搜索 - 如何根据数组中的值重新排序数组

javascript - 使用 highland.js 执行一系列异步任务并引用原始流数据

javascript - reshape HTML/CSS 中的视频元素

html - 如何找到css和js文件的地址?

javascript - 使 php 中的变量具有外部作用域

php - 使用 PHP 函数自动将宽度和高度属性添加到 <img> 标签

node.js - 在带有 Sequelize 的子查询中使用带有绑定(bind)参数的 EXISTS

javascript - Angular2 v3 组件路由器 : TypeError: Cannot read property 'split' of undefined

javascript - React hooks CRUD 应用程序中出现 TypeError : Cannot read property 'map' of undefined,