Node JS不断加载资源错误消息

时间:2013-07-21 19:17:58

标签: node.js

我目前正在测试node.js应用程序并尝试添加:

<link rel="stylesheet" href="assets/css/formalize.css" />
<script src="assets/js/jquery.formalize.js"></script> 

到我的代码,但不断收到错误消息:

Failed to load resource: the server responded with a status of 404 (Not Found) 

http://localhost:3000/assets/css/formalize.css

Failed to load resource: the server responded with a status of 404 (Not Found) 

http://localhost:3000/assets/js/jquery.formalize.js

知道我哪里出错了吗?这是我到目前为止的代码(在app.js中)

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

server.listen(3000);

app.get('/', function(req, res) {
    res.sendfile(__dirname + '/index.htm');
});

io.sockets.on('connection', function(socket) {
    socket.on('send message', function(data) {
        io.sockets.emit('new message', data);
    });
});

1 个答案:

答案 0 :(得分:12)

您需要将express.static中间件添加到app并使其指向包含静态资源的目录。

例如,如果您的目录结构设置如下:

app.js
index.htm
  static
    assets
      js
        jquery.formalize.js
      css
        formalize.css

您可以像这样指定静态资产目录:

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

并在您的html文件中引用您的文件,如下所示:

<link rel="stylesheet" href="/assets/css/formalize.css"/>
<script src="/assets/js/jquery.formalize.js"></script>