node.js 无法获取 CSS 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13395742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:39:27  来源:igfitidea点击:

Can not get CSS file

node.jsexpress

提问by angry kiwi

My directory set up is like this :

我的目录设置是这样的:

app.js
vews
  home.html
  css
    style.css

My home file is like this :

我的主文件是这样的:

<html>
<head>
  <title></title>
  <link rel="stylesheet" type="text/css" href="css/style.css" />
</head>
<body>

</body>
</html>

My app is like this :

我的应用程序是这样的:

var io   = require('socket.io'),
    url  = require('url'),
    sys  = require('sys'),
    express = require('express'),
    http=require('http');

var app = express();
var server = http.createServer(app);
var socket = io.listen(server);

app.engine('.html', require('ejs').__express);
app.set('views', __dirname + '/views');
app.set('view engine', 'html');

app.get('/', function(req, res){
    res.render('home');
});

app.listen(4000);
sys.puts('server running ' + 'now ' + Date.now());

The problem is when i run the app, css file can not be loaded.

问题是当我运行该应用程序时,无法加载 css 文件。

回答by Tolga Akyüz

Since .css files are static files you have to serve them to the clients. However, you do not serve static files as a express middleware. Add the following middleware to your express app and move the cssfolder under the publicdirectory (you should create a public directory)

由于 .css 文件是静态文件,因此您必须将它们提供给客户端。但是,您不会将静态文件作为快速中间件提供。将以下中间件添加到您的 express 应用程序并移动css目录下的文件夹public(您应该创建一个public directory

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

So your final directory structure should look like this

所以你的最终目录结构应该是这样的

app.js
views
  home.html
public
  css
    style.css

And do not forget to require pathmodule

并且不要忘记 requirepath模块

 var path = require('path')

回答by Rakesh Narayanan

Try this:

尝试这个:

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

This might solve the problem.

这可能会解决问题。