我尝试了两种方法来运行我的网站。
1)通过使用 Node
2)不使用node(我电脑上只有index.html)
然而,在链接样式表方面,结果是不同的。如果没有 Node ,样式标签中的样式表可以照常链接。但是,当使用node作为服务器时,样式表无法链接。
这是我的代码的结构。
/app
/server.js
/views
/statics
/index.html
/partials
/public
/javascript
/css
/main.css
/images
这里是index.html head标签
<link rel="stylesheet" type="text/css" media="screen" href="../../public/css/main.css">
服务器.js
const express = require('express')
const app = express()
const path = require('path')
// no need to use app.use(app.router) because of that update
// function signature express.static(root, [options])
app.use(express.static('public'));
// mount root to views/statics
app.use('/', express.static('views/statics'));
const PORT = process.env.PORT || 3000;
app.listen(PORT,() => {
console.log(`Server is listening on port ${PORT}`)
});
最佳答案
您似乎没有提供您的 Assets 可用的路径
app.use(express.static('public'));
根据the docs在这种情况下,公共(public)文件夹中的子文件夹将从根路径获取服务。
一般来说,您应该避免通过相对路径提供资源。在您的情况下 href="/css/main.css"
应该可以工作。 Node 充当服务器,您可以在 server.js
中定义给定资源可用的路径。您无法在文件系统的目录结构路径下访问它们
关于html - 样式表链接中的 href 属性在 Node 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55393132/