4

我是 socket.io 的新手,我已经遇到了问题,我认为是次要的。我已经用 npm 正确安装了 node.js 和 socket.io。然后只是为了测试,我从 socket.io 剪切并粘贴了一个代码示例,一切正常。现在,我想构建我的代码和文件夹,并且我创建了一个文件夹“client”来放置一个全新的 js 文件 client.js 和示例中的客户端代码。这是我的架构

/client
    client.js
index.html 
server.js

客户端.js:

var socket = io.connect('http://localhost:80');
  socket.on('news', function (data) {
    alert('sqd');
    console.log(data);
    socket.emit('my other event', { my: 'data' });
});

服务器.js

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

app.listen(80);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html', 'utf-8',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html ' + __dirname);
    }

    res.writeHead(200, {'Content-Type' : 'text/html'});
    res.end(data);
  });
}

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

索引.html

<!doctype html>
<html>
  <head>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    <title></title>

    <script type="text/javascript" src="/client/client.js"></script>
    <script type="text/javascript" src="/socket.io/socket.io.js"></script>

  </head>
  <body>
  </body>
</html>

当我在 localhost:80 刷新浏览器时,我的 client.js 出现错误:

Uncaught SyntaxError: Unexpected token <
Resource interpreted as Script but transferred with MIME type text/html

将我的js文件解释为js文件似乎有问题。我已经阅读了有关该问题的一些主题,但没有任何效果。

你能帮我吗 ?

谢谢:)


好的,我找到了解决方案...您必须在静态网络服务器中为每个文件请求指定内容类型。也许它可以帮助某人。这是处理函数:

function handler (req, res) {

  var filePath = req.url;

  if (filePath == '/') {
      filePath = './client/index.html';
  } else {
      filePath = './client/lib' + req.url;
  }

  var extname = path.extname(filePath);
  var contentType = 'text/html';

  switch (extname) {
    case '.js':
        contentType = 'text/javascript';
        break;
    case '.css':
        contentType = 'text/css';
        break;
  }

  path.exists(filePath, function(exists) {

    if (exists) {
        fs.readFile(filePath, function(error, content) {
            if (error) {
                res.writeHead(500);
                res.end();
            }
            else {
                res.writeHead(200, { 'Content-Type': contentType });
                res.end(content, 'utf-8');
            }
        });
    }
    else {
        res.writeHead(404);
        res.end();
    }
  });
}

希望这可以帮助某人。我喜欢发布问题并在没有帮助的情况下自行回复。不知何故,我绝望得太快了。我也喜欢在帖子中讲述我的生活:)好吧,我要吃点东西,多喝点咖啡!!!!

4

5 回答 5

3

太感谢了!这解决了我的问题!!我将开关更改为以下代码:

var extname = path.extname(filePath);
var contentTypesByExtention = {
  'html': 'text/html',
  'js':   'text/javascript',
  'css':  'text/css'
};
var contentType = contentTypesByExtention[extname] || 'text/plain';

它可能更容易维护:)

于 2012-08-08T13:04:46.670 回答
2

只有这样才能解决:

function handler (request, response) {
    var file = __dirname + (request.url == '/' ? '/index.html' : request.url);
    fs.readFile(file, function(error, data) {
        if (error) {
            response.writeHead(500);
            return response.end('Error loading index.html');
        }
        response.writeHead(200);
        response.end(data, 'utf-8');
    });
}
于 2013-05-25T18:44:52.540 回答
0

您也可以使用mime模块:

var mime = require('mime')
  , content_type = mime.lookup(filePath);

// handle the request here ...

response.setHeader('Content-Type', content_type);
response.writeHead(200);
response.end(data);
于 2013-07-06T19:08:41.303 回答
0

并且必须用fs.readFile闭包进行包裹,否则某些文件(尤其是最后一个文件)会被多次读取,而另一些则根本不会被读取。并且contentType不会按照您的意愿设置。这是因为fs.readFile. 当 html 文件只加载一个外部文件时,问题不会出现,但是当外部文件(css,js,png)加载多个时,它会像我上面指出的那样出现。(这个是我自己想出来的)

所以你的代码应该做一些改变,如下所示:

;(function (filename, contentType) {

    fs.readFile(filename, function(err, file) {
        // do the left stuff here
    });

}(filename, contentType)); 
于 2015-01-13T07:27:26.623 回答
0

这就是我需要的!谢谢你!我们将在顶部添加一个代码行

服务器.js

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')
  **, path = require('path')**
于 2013-05-07T22:31:55.490 回答