Socket.IO - require is not defined

后端 未结 8 2161
Happy的楠姐
Happy的楠姐 2020-12-28 08:49

I\'m trying to get socket.io working but now in Chrome I get the error:

Uncaught ReferenceError: require is not defined

client.php:9

8条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-28 09:23

    I had the same problem, and I confirm that @thejh's solution worked. I however was unsure as to "what" was the server when I read his recommendation. I do have MAMP running on port 80. And the code below would be the "node.js server", which runs on port 8001.

    Once I started the node.js server (ran the code below), a visit to http://localhost:4001/socket.io/socket.io.js returns the javascript file.

    /* Node.js server */
    
    var sys  = require('sys');
    var io   = require('socket.io');
    var http = require('http')
    server = http.createServer(function(req, res) { 
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.write('http server started');
      res.end(); 
    });
    server.listen(4001);
    
    
    // socket.io 
    var socket = io.listen(server); 
    socket.on('connection', function(client) {
    
      client.on('message', function(message) {
        // We're in!
        console.log('received client message '+ message);
      }); 
      client.on('disconnect', function() {});
      socket.send('welcome to the local node.js server!');
    });
    

    For those within Drupal, a drupal_add_js('http://localhost:4001/socket.io/socket.io.js', array('type' => 'external', 'group' => JS_LIBRARY)); within a hook_init does the trick.

提交回复
热议问题