Express 无法获取我的外部 CSS,为什么?

Express can't GET my external CSS, why?

控制台总是显示:GET http://localhost:8000/public/stylesheets/mystyle.css

当然,正如您将在下图中看到的那样,显然它指的是错误的路径。我用WebStorm自己生成了CSS.

href属性

app.js

var     express = require("express"),
            app = express(),
     bodyParser = require("body-parser"),
       mongoose = require ("mongoose");

app.use(express.static("public"));
app.set("view engine","ejs");
app.use(bodyParser.urlencoded({extended:true}));

header.ejs

<html>
<head>
    <title>My Blog</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.9/semantic.css" type="text/css">
    <link rel="stylesheet" type="text/css" href="../public/stylesheets/mystyle.css" >
</head>

项目路径:

您在(我假设的)HTML snippet/fragment 中有一个静态相对路径,由不同深度的多个目录中的多个页面共享。我还假设“public”是您网站的非公开根目录的名称。出于这个原因,您通常应该避免在 href=""src="" 属性中使用 ../ 相对路径,而是使用 root-relative / 或服务器生成的 application-root URLs,也称为"base"URLs。 (在 ASP.NET 中,这是通过 ~/ 完成的。Node.js does not currently 有一个内置的基础 URL 功能,但也有第三方包可以做到这一点。

改变这个:

<link rel="stylesheet" type="text/css" href="../public/stylesheets/mystyle.css" >

对此:

<link rel="stylesheet" type="text/css" href="/stylesheets/mystyle.css" >

顺便说一句,如果您的 styleseheets 目录仅包含 *.css 个文件,您应该考虑使用名为 styles 的目录,其中包含两个 .css 个文件 其他相关资产,例如 .css 文件引用的图像和字体,因为这使得 CSS 中的 URLs 更短并且没有父相对路径, 例如

foo#bar { background-image: url("../images/fooBg.png"); }

变为:

foo#bar { background-image: url("fooBg.png"); }

Express static 会为您将您的应用定向到您的静态文件(您已经处理好了),请尝试从您的视图 url 中删除 public,如下所示:

<html>
<head>
<title>My Blog</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.9/semantic.css" type="text/css">
<link rel="stylesheet" type="text/css" href="stylesheets/mystyle.css" >
</head>

如果其他答案都不行,可能与你用express设置静态目录的方式有关。如express docs中所述:

However, the path that you provide to the express.static function is relative to the directory from where you launch your node process. If you run the express app from another directory, it’s safer to use the absolute path of the directory that you want to serve:

也就是说,您可能需要像这样指定 public 目录的绝对路径:

var path = require('path');
...


app.use('/static', express.static(path.join(__dirname, 'public')))

...
<link rel="stylesheet" type="text/css" href="/stylesheets/mystyle.css" >