5

如何在我的 HTML 文件中包含 CSS 文件并在 Node.js 中呈现 HTML?

这就是我所做的:

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

然后是我去 localhost:8333/general.css 时的错误:

Cannot GET /general.css

我的模块渲染器脚本如下:

app.set('views', __dirname);
app.engine('html', engines.mustache);
app.set('view engine', 'html');

我该怎么做?

4

1 回答 1

9

You can to use Express' static middleware to serve static files like (client-side) JS and CSS:

app.use(express.static());

That will, by default, try and find static files in ./public (relative to the script you configure the middleware from):

yourproject/app.js   <-- if configured here
yourproject/public/  <-- it will look here

If you use this in your HTML/template:

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

The middleware will find and (if found) serve ./public/css/general.css.

If you want a setup where your CSS files are in the same directory as your application script, you can tell the middleware where to look for files by passing a directory as first argument:

app.use(express.static(__dirname));
于 2013-04-19T20:26:03.207 回答