Error view:

Uncaught ReferenceError: require is not defined **socket.io.js:11** 

Swears at the line:

 var client = require('socket.io-client'); 

Connection is:

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

Who faced?

  • In the folder with the project there is a folder node_modules in it module socket.io - IOleg
  • one
    Documentation do not read, do not connect. Nafig client you connect the server module?) In socket.io there is the same daddy: client. There is a file socket.io.js, in it and connect. - lampa
  • @IOleg, If you are given a comprehensive answer, mark it as correct (click on the check mark next to the selected answer). - Nicolas Chabanovsky

1 answer 1

This is because require for the node.js code, not the browser.

require is only running on the server. For example :

 var io = require('socket.io').listen(80); io.sockets.on('connection', function (socket) { socket.emit('news', { hello: 'world' }); socket.on('my other event', function (data) { console.log(data); }); }); 

Here’s how to use socket.io in a browser:

 <script src="/socket.io/socket.io.js"></script> <script> var socket = io.connect('http://localhost'); socket.on('news', function (data) { console.log(data); socket.emit('my other event', { my: 'data' }); }); </script> 

Of course, you need to make sure that socket.io is installed, and that the path /socket.io/socket.io.js exists, and that the server is providing it.

  • What is it? It’s too early for the client to connect the js library - that's the problem - IOleg
  • The node.js itself should give the browser a library at /socket.io/socket.io.js. But for some reason it does not do it - IOleg
  • Need to do npm install socket.io . Already done? - Peter Danilovich
  • Installed already. The problem persists - IOleg
  • When server.js starts, it issues info - socket.io started - IOleg