在下面的客户端代码中,我尝试显示一个与index.js和index.html位于同一目录中的图像(space.jpg)。当我访问服务器并且服务于index.html时,图像显示断开的链接。在提供静态HTML时是否存在Node的本机文件结构,我在这里没有考虑到这一点?
我在OS X(10.10.5)的本地环境中进行测试。
我有以下服务器代码(index.js):
System.Web.HttpContext.Current.User.Identity.Name
以下客户端代码(index.html):
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
socket.on('chat message', function(msg){
console.log('message: ' + msg);
io.emit('chat message', msg);
});
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
答案 0 :(得分:4)
您已经为index.html文件提供过服务,但您还没有在node.js代码中设置任何静态文件服务功能。
npm软件包很少,例如 node-static 和 express-static 。如果您愿意,可以将其用作中间件。
在项目中安装以下任何一项:
$ npm install express-static --save
然后您可以编辑index.js以使用express-static作为中间件。这将为项目根目录中的/ public下的所有文件提供服务。因此,您可以将所有资产(即图像,css,客户端js)放在/ public目录中。
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var static = require('express-static');
app.use(static(__dirname + '/public'));
在制作中,建议使用前面的http服务器或反向代理,如 nginx 或 apache 来提供静态文件,因为node.js不适合大资源文件。
答案 1 :(得分:3)
这是因为当浏览器尝试请求space.jpg
时,服务器不会回复任何内容,因为您只为/
创建了一个监听器,您可以在其中为{ {1}}。
要发送您的图片,您必须将其添加到您的代码中:
index.html
或者,您可以使用express.static
并将其设置为包含静态内容(例如图片)的特定路径。然后,这将提供相应的文件。