简体   繁体   中英

404 error using socket.io with express-generator

I am building the "hello world" of socket.io using the express-generator structure. When I execute my application I am getting "localhost/socket.io/socket.io.js 404 Uncaught ReferenceError: io is not defined". I installed the socket dependencies and I am creating the socket io routes into the index.js (generated by express-generator).

routes/index.js

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

var http = require('http').Server(express); //http;Server(serverVar)
var io = require('socket.io')(http);

views/index.ejs

<script src="socket.io/socket.io.js"></script>
var socket = io();

I suggest you to use the global structure to define routes with express.js and you need to use the io.connect(path) function to connect your web page to your node.js server

routes/index.js

var express=require('express');
var http=require('http');
var app=express();
var server=http.createServer(app).listen(process.env.PORT);
var io=require('socket.io').listen(server);

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

and use the app.get method to handel inexistant URL requests you can put any page name in the place of Default.html

app.get('*',function(request,response){
response.redirect('Default.html');
});

then use this code at your client-side file views/index.ejs

 var socket;
 $(document).ready(function(){
 socket=io.connect(window.location.hostname);});

you can Change your "window.location.hostname" gloabl variable with your url local path in case an error occurs

Had the same problem after generating express project with express-generator tool. With this config all works like a charm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM