html - 样式表链接中的 href 属性在 Node 中不起作用

标签 html node.js express

我尝试了两种方法来运行我的网站。 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/

相关文章:

javascript - 按钮在 iPhone 上的 Safari 中不起作用

html - 需要在文本内显示具有设定宽度和高度的跨度

node.js - 如果输入数组为空或 mongoose 聚合中不存在,如何跳过查询执行

javascript - 如何在 ejs 中使用 if 语句?

html - TinyMCE 从自定义标签中删除属性

Javascript 在同一张图片上单击播放和暂停歌曲

node.js - 如何仅获取两个集合之间未加入(排除)的文档?

javascript - Nodemailer 发送匿名电子邮件

node.js - 我可以知道使用 Express 渲染模板客户端与服务器端的最佳方法吗?还有性能?

mongodb - 如何使用 GridFS 使用 Node.js 和 Mongoose 存储图像