I am new to socket.io and I already have a problem, I think a little. I installed node.js correctly and socket.io also with npm. Then just for testing, I cut and paste the sample code from socket.io and everything works fine. Now, I want to strcuture my code and folders, and I created the client folder to put a new 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>
When I update my browser on localhost: 80 I have an error on my client.js:
Uncaught SyntaxError: Unexpected token < Resource interpreted as Script but transferred with MIME type text/html
There seems to be a problem interpreting my js file as a js file. I read some topics in the question, but nothing works.
Can you help me?
Thanx :)
Ok, I found a solution ... You must specify the content type for each file request in a static web server. Maybe this can 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 helps someone. I love to post problems and respond on my own without help. Somehow it seems to me that I got distracted too quickly. And I also like to tell my life in fasting :) Well, I'm going to eat something and drink more coffee.