【问题标题】:Can't link to a stylesheet or a script in HTML served by Express无法链接到 Express 提供的 HTML 中的样式表或脚本
【发布时间】:2021-03-20 19:38:44
【问题描述】:

我正在尝试将我的 Express 应用程序的代码拆分为多个文件。但是,我不能使用<link href><script src> 链接到样式表或脚本。

这是我的 index.js 中的相关代码:

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

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/public/index.html');
});

我的文件结构是:

.
├── index.js
└── public
    ├── favicon.ico
    └── index.html

有人可以帮忙吗?

【问题讨论】:

  • 您的快递程序仅服务于public/index.html。您没有任何代码来提供样式表或脚本。
  • @Quentin 你能用 res.sendFile 提供样式表吗?
  • 是的。这是个坏主意,但你可以。

标签: javascript html css node.js express


【解决方案1】:

你有:

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/public/index.html');
});

所以当浏览器请求/时,你会发送index.html

这就是你所拥有的全部

如果浏览器要求任何内容,否则您将向其发送 404 错误页面。

如果您想提供静态文件,请使用 static 模块(其中包括您通过显式路由提供的 index.html 文件)。

getting started guide! 对此进行了介绍!

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

【讨论】:

  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 2020-06-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-05
  • 1970-01-01
相关资源
最近更新 更多