node.js - Node JS 不断收到无法加载资源错误消息

标签 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);
    });
});

最佳答案

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

例如,如果你的目录结构是这样设置的:

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

您可以像这样指定您的静态 Assets 目录:

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

并像这样在您的 html 文件中引用您的文件:

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

关于node.js - Node JS 不断收到无法加载资源错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17775944/

相关文章:

node.js - Phonegap : two kinds of installations, 有什么区别?

javascript - 如何从数组中提取特定的一段json

node.js - Redis:如何通过命名空间/规则一次保存(和读取)键值对?

Javascript 对象打印为对象对象

node.js - 如何将对象发送给 Handlebars 中的助手?

javascript - ExpressJS 将变量传递给 JavaScript

angularjs - Node、Express JS 中发送 URL 参数

javascript - 是否可以在 node.js 服务器上运行 Three.js WebGLRenderer?

javascript - MongoDB 重复键错误

Node.js 流式传输 gzip http 响应