简体   繁体   English

未获取/应用 Express 服务器公共样式表

[英]Express server public stylesheet not being fetched/applied

I'm learning how to serve pages with node, express and ejs.我正在学习如何使用 node、express 和 ejs 提供页面。 I am trying to link a stylesheet to index.ejs by using a public folder but when I visit the page in my browser there are no styles, and the network tab doesn't show a request for the stylesheet.我试图通过使用公共文件夹将样式表链接到 index.ejs,但是当我在浏览器中访问该页面时,没有样式,并且网络选项卡不显示对样式表的请求。 When I go to localhost:3000/styles.css, the file shows up no problem.当我转到 localhost:3000/styles.css 时,文件显示没有问题。 The files look like this:这些文件如下所示:

index.ejs索引.ejs

<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sam's Site | <%= title %></title>
    <link rel="stylesheet" src="/styles.css" type="text/css">
  </head>

  <body>
  ...
  </body>
</html>

app.js应用程序.js

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

app.set('view engine', 'ejs');

app.listen(3000);

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

app.get('/', (req, res) => {
  res.render('index', {title: 'Home');
});

app.js is in the top level folder, index.ejs is in a views folder, and styles.css is in a public folder. app.js 在顶级文件夹中,index.ejs 在 views 文件夹中,而 styles.css 在 public 文件夹中。 When I inspect it in the browser, the header shows up normally and the link tag looks like it should be working.当我在浏览器中检查它时,标头正常显示并且链接标签看起来应该可以正常工作。

I've tried changing the source to several different variations of the path to styles.css and I've made sure styles contains valid css.我已经尝试将源更改为 styles.css 路径的几种不同变体,并且我已确保样式包含有效的 css。 Can anyone explain why the stylesheet is not being loaded?谁能解释为什么没有加载样式表?

use:采用:

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

instead of: app.use(express.static(__dirname + '/public'));而不是: app.use(express.static(__dirname + '/public'));

You are using public folder as default in express.您在 express 中默认使用公用文件夹。 So, no need to specify the path.因此,无需指定路径。

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

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