2016-03-19 5 views
0

私はsocket.ioを学び始めてthis example of chatを使い始めました。Node.js socket.io webserverはindex.html以外のファイルを提供します

ip:8080/public/index.htmlに行くと、ブラウザのクライアント側で使用される他のJSスクリプトなどの他のファイルにもアクセスする必要があります。しかし、私は、このようなスクリプトの負荷をかけるとき:

<script src="/js/phaser.js" type="text/javascript"></script> 

Webサーバがそれを返さない、と私はこのハンドラのコードでそれを必要とします。

私はこのコードを持っている:

var app = require('http').createServer(handler) 
var io = require('socket.io')(app); 
var fs = require('fs'); 

app.listen(8080); 

function handler (req, res) { 
    console.log(req.headers.referer); 
    fs.readFile(__dirname + '/public/index.html', // <--- I need here put filename which client wants it, but when I console.log to req it return HUGE data, I not found anythink usefull 
    function (err, data) { 
    if (err) { 
     res.writeHead(500); 
     return res.end('Error loading index.html'); 
    } 

    res.writeHead(200); 
    res.end(data); 
    }); 
} 

io.on('connection', function (socket) { 
    socket.emit('news', { hello: 'world' }); 
    socket.on('my other event', function (data) { 
    socket.broadcast.emit('new message', data); 
    console.log(data); 
    }); 
    socket.on('msg', function(data){ 
    console.log(data); 
    }) 
}); 
+0

はおそらく() '自動的に1行のコードで静的ファイルのディレクトリを提供するために、' express.staticを[Expressサーバ](http://expressjs.com/)モジュールを使用して、使用したいです。 node.jsはデフォルトではファイルを提供しないため、応答したいリクエストに対する応答にコードを明示的に追加する必要があります。処理する着信要求ごとに特別なコードを使用するか、1ブロックのコードでディレクトリ階層全体を処理することができます。 – jfriend00

答えて

0

あなたはあなたの* .jsのファイルなどの静的ファイルを提供するためExpress staticを使用することができます。

関連する問題