简体   繁体   中英

Can not Run Node.js server file

I am new to Node.js. I have my NodeServer.js file which has below code.

var express = require("express");
var app = express();
var port = 60000;

var io = require('socket.io').listen(app.listen(port));
console.log("Listening on port " + port);

io.sockets.on('connection', function (socket) {
    socket.emit('message', { message: 'welcome to the chat' });
    socket.on('send', function (data) {
        io.sockets.emit('message', data);
    });
});

When I run this from command prompt , by below code

D:\Path to my application>Node NodeServer.js

It shows message like

   info  - socket.io started
   Listening on port 60000

But when I try to connect to this port from browser by http://127.0.0.1:60000 , it shows me below error in command prompt

D:\Path to my application\node_modules\expres
s\lib\application.js:119
  this._router.handle(req, res, function(err) {
               ^
TypeError: Cannot call method 'handle' of undefined

What am I Doing wrong?

Above issue is solved:

Below is my EDIT

Below is my client Script

$(document).ready(function () {   

    var socket = io.connect('http://127.0.0.1:60000');

});

Below is my desing

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="jquery-1.10.1.min.js" type="text/javascript"></script>
    <script src="http://127.0.0.1:60000/socket.io/socket.io.js" type="text/javascript"></script>
    <script src="NodeClient.js" type="text/javascript"></script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    </div>
    </form>
</body>
</html>

When I run my application I get error of "NetworkError: 404 Not Found - http://127.0.0.1:60000/socket.io/socket.io.js"

I have solved my issue by below steps.

  1. I moved my ClientScript to one specific folder(Scripts).(Say my client Script's name is NodeClient.js)
  2. I removed app.get("/", function(req,res){ your logic should go here }); function from Server script.
  3. added below code app.use(express.static(__dirname + '/Scripts'));

Now it is working the way I want. I don't know whether it is right way or not, but it is working now for me.

change the following line

 var io = require('socket.io').listen(app.listen(port));

by

 var io = require('socket.io').listen(port);

app.listen(port) returns an object but we have to run the socket.io and express in same port. To do that simply pass the port variable

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