【问题标题】:Why is html page sent by express.js route not connected to a css stylesheet?为什么 express.js 路由发送的 html 页面没有连接到 css 样式表?
【发布时间】:2019-09-17 01:05:09
【问题描述】:

所以我有导入路由器的 server.js 文件

const path = require("path");
const express = require("express");
const app = express();

const PORT = 8080;

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

app.use(require('./app/routing/htmlRoutes')); 

路由器长这样

const path = require("path");
var express = require('express');
var router = express.Router();



router.get('/', function(req, res) {
    res.sendFile('home.html', { root: path.join(__dirname, '../public') });
});

router.get('/survey', function(req, res) {
    res.sendFile('survey.html', { root: path.join(__dirname, '../public') });
});


module.exports = router;

确实有效!它呈现 html 页面,但是这些 html 页面有 css 样式表连接到它们并位于同一目录中,但它们呈现为空白 html 表(无样式)...... 如何让它们在考虑 css 样式表的情况下呈现?

【问题讨论】:

  • 你在哪里提供这些 css 文件?
  • 与html文件在同一目录下...'public'
  • 你的意思是我在哪里存储它们?
  • 不,我的意思是你在哪里/如何为他们服务。您的脚本提供两个 html 文件,但不提供 css 文件,因此当您的浏览器尝试加载它们时,它显然会失败并显示 404。
  • 是的,您也需要为他们服务。 Express 不会自动连接它们。

标签: javascript node.js express routing


【解决方案1】:

当浏览器遇到加载的 html 文件的样式引用时,它会尝试加载 src 属性中指定的文件。现在您的服务器脚本没有路由。如果您为该特定 css 文件添加路由,它将加载 css。但是正如 Irshad 所说,执行此操作的标准方法是为所有静态文件添加路由。

app.use(express.static("public"))

现在,您只在每次请求根时发送 home.html。

更改您的代码以从 req 中读取请求的文件并提供该文件,无论它可能是什么。

【讨论】:

    【解决方案2】:

    为什么不将中间件设置为从公共文件夹app.use(express.static("public"))提供静态文件(css、html)

    See the working example

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-27
      • 1970-01-01
      • 2020-02-18
      • 2016-07-30
      • 2019-08-08
      • 2012-04-10
      • 2019-09-29
      相关资源
      最近更新 更多