简体   繁体   English

为什么 express.js 路由发送的 html 页面未连接到 css 样式表?

[英]Why is html page sent by express.js route not connected to a css stylesheet?

So I have server.js file that imports a router所以我有导入路由器的 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')); 

The router looks like this路由器长这个样子

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;

It does work!它确实有效! It renders html pages, however those html pages have css stylesheets hooked up to them and located in the same directory, but they render as blank html sheets (unstyled)... How do I make them render with css stylesheets taken into account?它呈现 html 页面,但是这些 html 页面将 css 样式表连接到它们并位于同一目录中,但它们呈现为空白的 html 表(无样式)......我如何使它们在考虑 css 样式表的情况下呈现?

When the browser encounters the style reference of the loaded html file, it tries to load the file specified in the src attribute.当浏览器遇到加载的 html 文件的样式引用时,它会尝试加载 src 属性中指定的文件。 Now your server script doesn't have a route for that.现在您的服务器脚本没有相应的路由。 It will load the css if you add a route for that specific css file.如果您为该特定 css 文件添加路由,它将加载 css。 However as Irshad said, the standard way to do this is to add a route for all the static files.但是,正如 Irshad 所说,执行此操作的标准方法是为所有静态文件添加路由。

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

Right now, you are only sending home.html everytim the root is requested.现在,您只在每次请求根时发送 home.html。

Change your code to read the requested file from the req and serve that file whatever it may be.更改您的代码以从 req 读取请求的文件并提供该文件,无论它是什么。

Why not set the middleware to serve static files (css, html) from public folder app.use(express.static("public"))为什么不将中间件设置为从公共文件夹app.use(express.static("public"))提供静态文件(css、html app.use(express.static("public"))

See the working example查看工作示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM