Socket.io.js not found (node.js + express + socket

2019-08-10 17:39发布

问题:

I've been checking other related answers such as:

  • node.js /socket.io/socket.io.js not found
  • Socket.io not being served by Node.js server
  • socket.io.js not found on client
  • Configuring 'simplest' node.js + socket.IO + Express server

But I didn't find the solution to my problem.

This is exactly what I did:

Installed node through the windows executable and then:

express node6 --hogan --ejs 
cd node6
npm install
npm install socket.io

npm start

My app.js is the default one but I added the following lines to link it with socket.io:

var http = require('http');
var server = http.createServer(app);
var io = require('socket.io')(server);
io.listen(http);
http.listen(3000);

Here's the complete app.js file.

I also tried to copy and paste the examples for Node http server and Using with Express 3/4 or the app.js detailed in the socket.io docs, but both of them throw errors when calling npm start.

Then, in my hoggn view, I'm trying to load socket.io this way:

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

As far as I know, node.js should get it automatically, but it doesn't in my case. Why? Express version: 4.2.0

This is the error page:

Not Found
404
Error: Not Found
at Layer.app.use.res.render.message [as handle] (C:\inetpub\wwwroot\node6\app.js:29:15)
at trim_prefix (C:\inetpub\wwwroot\node6\node_modules\express\lib\router\index.js:240:15)
at C:\inetpub\wwwroot\node6\node_modules\express\lib\router\index.js:208:9
at Function.proto.process_params (C:\inetpub\wwwroot\node6\node_modules\express\lib\router\index.js:269:12)
at next (C:\inetpub\wwwroot\node6\node_modules\express\lib\router\index.js:199:19)
at next (C:\inetpub\wwwroot\node6\node_modules\express\lib\router\index.js:176:38)
at C:\inetpub\wwwroot\node6\node_modules\express\lib\router\index.js:137:5
at C:\inetpub\wwwroot\node6\node_modules\express\lib\router\index.js:250:10
at next (C:\inetpub\wwwroot\node6\node_modules\express\lib\router\index.js:160:14)
at next (C:\inetpub\wwwroot\node6\node_modules\express\lib\router\index.js:176:38)

回答1:

Instead of doing npm install socket.io you have to do npm install socket.io --save so the socket.io module gets installed in your web development folder (run this command at the base location/where your index.html or index.php is). This installs socket.io to the area in which the command is run, not globally, and, in addition, it automatically corrects/updates your package.json file so node.js knows that it is there.

Then change your source path from '/socket.io/socket.io.js' to 'http://' + location.hostname + ':3000/socket.io/socket.io.js'.