簡體   English   中英

Node.js socket.io Web服務器提供除index.html之外的其他文件

[英]Node.js socket.io webserver provide other file than index.html

我開始學習socket.io並使用此聊天示例

當我訪問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);
  })
});

您可以使用Express static來提供靜態文件,例如* .js文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM