Not Found, Using Express-generator Generated Project","text":" i am trying to use an express-generator generated project to reproduce the ...","answerCount":1,"upvoteCount":28,"acceptedAnswer":{"@type":"Answer","text":"After a long time searching, I have found the best answer to my question. Please refer to A simple express socket.io tutorial using express generators. ","upvoteCount":28,"url":"http://tutorialmeta.com/question/client-side-script-src-socket-io-socket-io-js-script-not-found-using-exp"},"suggestedAnswer":[]}} Client Side <script Src="/socket.io/socket.io.js"></script> Not Found, Using Express-generator Generated Project Not Found, Using Express-generator Generated Project"> Not Found, Using Express-generator Generated Project">
Ad

Client Side Not Found, Using Express-generator Generated Project


I am trying to use an Express-generator generated project to reproduce the "chat-example" given in Socket.IO official website. I want to keep the generated structure intact. I nearly keep everything the same as the "chat-example" and just try to fit it into an Express-generator generated project. The problem I encounter is that the client-side is not able to invoke the script socket.io.js. Here I post the project file structure, the code that have changed/added, and the error messages.
Could someone please be so kind to help me? Thank you very much!

1. Project File Structure (*:change has been made; **:newly added file.)

ioChat (project name)
-- bin
   -- www (*)
-- node_modules
   -- socket.io 
   -- socket.io-adapter
   -- socket.io-client
   -- socket.io-parser
   -- (many other modules)
-- public
   -- images
   -- javascripts
   -- stylesheets
      -- style.css (*)
   -- index.html (**)
-- routes
   -- index.js (*)
   -- users.js
-- views
   -- error.jade
   -- index.jade
   -- layout.jade
-- app.js
-- package-lock.json
-- package.json


2. bin\www (commented with //+++ are the added code)

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');
var debug = require('debug')('iochat:server');
var http = require('http');
var io = require('socket.io')(http); //++++


/**
 * Get port from environment and store in Express.
 */

var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);

/**
 * Create HTTP server.
 */

var server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);


// socket io for realtime messaging  //++++
io.on("connection", function(socket){
    socket.on("chat", function(msgin){
        var msgout = { name: msgin.name, msg: msgin.msg , mtime: new Date()};
        io.emit("chat",msgout);
    });
});


/**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
  var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
  }

  return false;
}

/**
 * Event listener for HTTP server "error" event.
 */

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}


3. public\index.html (newly added)

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>ioChat</title>
        <link rel="stylesheet" type="text/css" target="_blank" rel="nofollow noreferrer" href="stylesheets/style.css">
        <script src="/socket.io/socket.io.js"></script>
        <!-- <script src="../node_modules/socket.io-client/dist/socket.io.js"></script> -->
        <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
        <script>
            $(function(){
                var socket = io();

                $("#btnSend").on("click",function(){
                    var msgout = {name:$("#senderName").val(), msg:$("#msg").val()};
                    socket.emit('chat',msgout);
                    $("#msg").val("");
                });

                socket.on("chat",function(msgin){
                    $("#msgList").append($("<li>").text(`${msgin.name} says: ${msgin.msg} (msgin.mtime)`));
                });

            });     
        </script>
    </head> 

    <body>
        <ul id="msgList"></ul>
        <div class="iptArea">
            <label for="name" class="msgItems">Name:</label>
            <input type="text" id="senderName"  class="msgItems"/
            <label for="msg"  class="msgItems">Message:</label>
            <input type="text" id="msg"  class="msgItems"/>
            <button class="msgItems" id="btnSend">Send</button>
        </div>
    </body>
</html>


4. routes\index.js (commented with //+++ are the added code)

var express = require('express');
var router = express.Router();

/* GET home page. Let http://localhost:3000 directly go to public\index.html*/
router.get('/'); //+++ 

module.exports = router;


5. Server-side error message (apparently it is 404 not found):

GET /socket.io/socket.io.js 404 34.641 ms - 1142


6. Client-side error message:

GET http://localhost:3000/socket.io/socket.io.js net::ERR_ABORTED 404 (Not Found)
Uncaught ReferenceError: io is not defined
Ad

Answer

After a long time searching, I have found the best answer to my question. Please refer to A simple express socket.io tutorial using express generators.

Ad
source: stackoverflow.com
Ad