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