naik3 naik3 - 3 months ago 24
Node.js Question

Error running socket.io and express-nodejs setup

I was working on nodejs executing python scripts using spawn and socket.io methods. I am getting output on the console. but I am not able to display it on the browser. It is showing error.I have pasted the error below. Can any one please help me in solving this problem. I have got this example from this stackoverflow
Here i am pasting my code: sample.py

import random, time
for x in range(10):
print(str(random.randint(23,28))+" C")
time.sleep(random.uniform(0.4,5))


index.js

var express = require("express");
var path = require('path');
var bodyParser = require('body-parser');
var fs = require('fs');
var spawn = require('child_process').spawn;
var http = require('http').Server(app);
var io = require('socket.io')(http);

var app = express();
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.post('/showtemp',function(req,res){
var pathtoScript = spawn('python', ["../External_scripts/sample.py"]);
pathtoScript.stdout.on('data', function (output) {
var val = String(output);
console.log(val);
io.sockets.emit('response', { data: val});
});
})
var server = app.listen(8082,'0.0.0.0', function () {

var port = server.address().port

console.log("App is listening at %s", port)

});


And index.html page

<!doctype html>
<html>
<head>
<title>Live temperature</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div id="liveTemp">Loading...</div>

<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
var socket = io();
socket.on('response',function(msg){
console.log("msg");
$('#liveTemp').html(msg.data);
})
});
</script>

</body>
</html>


I am getting this error

GET http://localhost:8082/socket.io/?EIO=3&transport=polling&t=LQSVrTN 404 (Not Found)
GET http://localhost:8082/socket.io/?EIO=3&transport=polling&t=LQSVrTN 404 (Not Found)

Answer

You haven't started a web server anywhere or hooked socket.io to it. There are several different ways to do this, but here's one that works:

var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);

server.listen(80);

Note: You must see a server.listen() (or equivalent) somewhere. And, you need to pass the server to socket.io so it can hook into it.

You can also do this where you don't directly need to load the http module yourself:

var express = require('express');
var app = express();
var server = app.listen(80);
var io = require('socket.io')(server);

socket.io documentation for several different options here.

Comments