socket.io & express: 404 not found

后端 未结 1 689
不思量自难忘°
不思量自难忘° 2021-01-22 20:42

My app.js

const express = require(\'express\'),
      morgan = require(\'morgan\'),
      bodyParser = require(\'body-parser\'),
      path = require(\'path\'),
         


        
相关标签:
1条回答
  • 2021-01-22 20:50

    If you're going to do this:

    server = require('http').createServer(app),
    

    Then, you can't do:

    app.listen(PORT, ...);
    

    because app.listen() will create a new and different server and socket.io will not be associated with that one.

    Instead, you need to do:

    server.listen(PORT, ...)
    

    using the server value from app.js. And, if you want to require() in the server from app.js, you also need to export it from app.js (something else I don't see your code doing).


    For reference, the code for app.listen(), does this:

    app.listen = function listen() {
      var server = http.createServer(this);
      return server.listen.apply(server, arguments);
    };
    

    You can see how it creates a different server than the one you passed to socket.io. Thus the one you passed to socket.io is never started and thus socket.io does not work.

    0 讨论(0)
提交回复
热议问题