Node.js /socket.io/socket.io.js not found express 4.0

后端 未结 2 2003
野性不改
野性不改 2021-01-05 17:44

So I\'m trying to get chat working on my website, and when I was testing locally it worked great, because port 8080 on my localhost was available and all that good stuff. Bu

相关标签:
2条回答
  • 2021-01-05 18:36

    What happens when you go to http://localhost:8080/socket.io/socket.io.js?

    Does it 404? If it does you need to make sure you have it in a directory that Express is set to serve statically.

    app.use(express.static(__dirname + '/public'));
    

    Then put your socket.io.js file in public/socket.io/socket.io.js (relative to your app.js file)

    Restart your server and see if that fixes it.

    Basically, Express doesn't serve files statically from the file system unless you explicitly tell it where to map from.

    0 讨论(0)
  • 2021-01-05 18:37

    Do you have an explicit route in express which catches all other routes? Something like this perhaps:

    app.get("/", handlers.home);
    app.get("/..." ...);
    ...
    app.get("*", handlers.error);
    

    This might keep socket.io from being able to host it's own js file for the client. There is an easy way to fix this, since you probably already have a public or static folder setup in express. Something like:

    app.use(express.static("public"));

    Make a new folder called socket.io and copy over the appropriate socket.io.js file into said folder, and all should be well. However note that there are two files named socket.io.js!! So, if you see something like "Uncaught ReferenceError: require is not defined" it means you copied the "node-ey" server side file. Here is the correct client file to copy:

    app_dir/node_modules/socket.io/node_modules/socket.io-client/dist/socket.io.min.js

    Note @BHendricks: I would have just posted as a reply to your comment, but I currently lack the required reputation.

    Edit: The OPs question probably has more to do with the "localhost" issue. When connecting from a client (say your home IP), as far as your browser knows - localhost implies a connection with the machine which is locally hosting stuff. Since your home machine (or phone) does not host socket.io, this is failing.

    What you need to do is have your server embed the socket connection information (either a fully qualified hostname, ip etc). This can be done when the server "renders" the page with the client connection.

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