socket.io 和 differents 文件夹 --- 找到解决方案 [英] socket.io and differents folders --- solution found

查看:15
本文介绍了socket.io 和 differents 文件夹 --- 找到解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new to socket.io and i already have a problem, minor i think. I have installed node.js properly and socket.io too with npm. Then just for testing i cut and paste a sample of code from socket.io and everything works well. Now, i want to strcuture my code and folders and i have created a folder "client" to put a fresh new js file client.js with the client code from the example. Here is my architecture

/client
    client.js
index.html 
server.js

client.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' });
});

server.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);
  });
});

index.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 出现错误:

When i refresh my browser at localhost:80 i have a error on my client.js :

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

好像把我的js文件解释成js文件有问题.我已经阅读了有关该问题的一些主题,但没有任何效果.

It seems that there's a problem to interpret my js file as a js file. I've read some threads on the question but nothing works.

你能帮我吗?

谢谢:)

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

Ok i've found a solution... You have to specify the content type for each file request in a static webserver. May be it could help someone. Here is the handler function :

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();
    }
  });
}

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

Hope this can help someone. I love to post a problem and respond by myself with no help. Somehow it meens that i'm desesperate too fast. And i love to tell my life in a post too :) Ok i'm gonna eat something and drink more coffee !!!

推荐答案

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

Thank you so much! This solved my problem!! And I changed the switch to following code:

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

可能更容易维护:)

这篇关于socket.io 和 differents 文件夹 --- 找到解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆