Node.js - Socket.io client file is not served by the core node web server

I am very new to Node.js and Socket.io. However, when I use it, I created a very simple web server, I can not load the socket.io client file (I get 404).

I am trying to use this client side code:

<script src="/socket.io/socket.io.js"></script> 

I understand that Node should pick this up and solve it? This is done on a much simpler web server example.

My example web server where it is NOT allowed is as follows:

 var server = http.createServer(function (request, response) { console.log('request starting...'); var filePath = '.' + request.url; if (filePath == './') filePath = './index.html'; 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) { response.writeHead(500); response.end(); } else { response.writeHead(200, { 'Content-Type': contentType }); response.end(content, 'utf-8'); } }); } else { response.writeHead(404); response.end(); } }); 

My web server code, where allowed, is as follows:

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

Can anyone advise what causes it to not serve the socket.io file on the client using the first example web server?

Best regards, Ben.

+4
source share
1 answer

You are probably using Socket.IO on a different port, so include the file in the following format:

server: port /socket.io/socket.io.js

+11
source

Source: https://habr.com/ru/post/1385683/


All Articles