I'm trying to incorporate a live user count on my website http://clickthebutton.herokuapp.com which uses Express JS. When trying to install socket.io I get this error:
GET /socket.io/socket.io.js 404 1.911 ms - 1091
Yes, I have used 'npm install socket.io --save'
I have looked around for answers, tried them and nothing has helped. If anyone thinks they know what's happening, a response would be well appreciated! Here's my code:
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var io = require('socket.io')(app);
var routes = require('./routes/index');
var users = require('./routes/users');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var server = app.listen(app.get('port'), function () {
console.log('server listening on port ' + server.address().port);
})
var io = require('socket.io').listen(server);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
index.ejs
<!-- socket.io -->
<script src="socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect();
</script>
</div>
</center>
</body>
routes/index.js
var express = require('express');
var router = express.Router();
var redis = require('redis'), client = redis.createClient(secret, "secret"); client.auth("secret", function() {console.log("Connected!");});
var app = express();
var server = require('http').Server(app);
var http = require('http');
var io = require('socket.io').listen(server);
io.on('connection', function(socket){
console.log('a user connected');
console.log(Object.keys(io.sockets.connected));
});
io.on('connection', function (socket) {
console.log('Socket.io connected!')
});
I only copy/pasted the code that referenced socket.io
Thanks!
In app.js alone you're creating three instances of socket.io, and once again in routes/index.js. There should be only one throughout your entire app.
A common setup for Express looks like this:
var app = require('express')();
var server = app.listen(app.get('port'), function () {
console.log('server listening on port ' + server.address().port);
});
var io = require('socket.io')(server);
If you need to reference either app, server or io in other files, you need to pass it as a variable.
EDIT: because you're using an express-generator based setup, the HTTP server will be created in bin/www and not app.js. In that case, you also need to create the socket.io server there:
/**
* Create HTTP server.
*/
var server = http.createServer(app);
var io = require('socket.io')(server); // add this line
Again, if you need to reference io somewhere else in your codebase, you need to pass it along from there.
Related
I am trying to upload a single image using python code to a node js express server. The python code is:
import requests
url = 'http://localhost:9000/testAPI/uploadphoto'
files = {'file': ('photo', open('test.jpg', 'rb'))}
ret = requests.post(url, files=files)
print ret
For the app.js, it is mostly following the default template:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var cors = require('cors');
var bodyParser= require('body-parser')
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var testAPIRouter = require("./routes/testAPI");
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(cors());
app.use(logger('dev'));
app.use(express.json());
//app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.urlencoded({extended: true}))
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use("/testAPI", testAPIRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
and I am using the router testAPI for handling the POST:
var express = require('express');
var multer = require('multer');
var router = express.Router();
// SET STORAGE
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '/uploads')
},
filename: function (req, file, cb) {
var filename = file.originalname;
var fileExtension = filename.split(".")[1];
cb(null, Date.now() + "_" + filename);
}
});
var upload = multer({ storage: storage });
router.get('/', function(req, res, next) {
console.log("test");
res.send('API is working properly');
});
router.post('/uploadphoto', upload.single('photo', (req, res, next) => {
const file = req.file;
if (!file) {
const error = new Error('Please upload a file')
error.httpStatusCode = 400
return next(error)
}
res.send('Photo uploaded');
}));
module.exports = router;
When I run the python code, the server returns 500. In my node js directory, I have an uploads folder created.
At the first you should run your node server project in port 9000
Your npm start probably calls your bin/www file. Which contains the listen invocation to start your app.
Many people set up their app this way. eg. app.js to define and configure their app, and something like bin/www to actual get the server running. This way they can include the app.js into other parts, say tests, without actually starting the server when you require it.
Figured it out. Since my server is started in the bin/www file as opposed to the app.js file, from the terminal I went into my bin directory and then called
node wwww
or
nodemon www
or add this code to the app.js and then run it with node app.js to listen port 9000
const port = 9000;
app.listen(port, () => console.log(Example app listening on port ${port}!))
Thanks for help in advance. I am getting following state from my console See Server running console log. Below Snippet is my app.js code where express and node server running. If you see my socket code my console.log underneath socket connection is not showing in server logs. Socket is not listening my messages.
I have also upload my sample of code at github, here you can find that (github.com/ferozpuri/node-app) client socket code is in SocketController.js an Angular controller file.
Here is my app.js file code, As you can see console log for "Connection was made" never show. and same with socket console.
var express = require('express');
var http = require('http');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var engines = require('consolidate');
var routes = require('./routes');
var users = require('./routes/user');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
// view engine setup
//app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'jade');
app.engine('html', engines.nunjucks);
app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'views'));
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
app.get('/', routes.index);
app.get('/users', users.list);
/// catch 404 and forwarding to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.render('error', {
message: err.message,
error: {}
});
});
io.on('connection', function (socket) {
console.log('A connection was made!');
socket.on('chat.message', function (message) {
console.log('New Message : ' + message);
});
});
module.exports = app;
I am not getting socket response from node server. PLease let me know if i not explain this properly or any thing is not here.
Server listing on port you can see this in screenshort or my project structure
Project structure & app listening port OR NPM START CODE
You have set up all handlers but you did not initialize app.
http.listen(app.get('port'), function() {
console.log('App is listening on port', app.get('port'));
});
You did not start your server. In your code, your server is created with this line:
var server = require('http').Server(app);
So, sometime after that, you need to add:
server.listen(80); // or use whatever port number you want the server on
I have resolved this issue by adding following line of code under constructing my express/after var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(3000);
#jfriend00 and #Sablor, Thanks both of you for show me right direction. my server already running on port "3000" so with port 80 its was not working. because it is conflicting with my XAMPP server. Thanks you guys for participating
I have a Experss.js framework and Node.js with a request to MS SQL database on the server side.
I want to get a data(in JSON or array) from server and send to Cliend side.
I don't understand how can I write routers for another server on the Client side.
server.js
npm start
http://localhost:5000/
Code:
var sql = require("mssql");
var express = require('express');
var app = express();
var http = require('http')
var query = "SELECT AVG([sta_waittime]) AS Spalte FROM [DialogMaster_TEST].[dwh].[anruf_stat] WHERE CONVERT(DATE,sta_timestamp) = CONVERT(DATE,CONVERT(DATE,'2016-08-01')) ";
app.get('/', function (req, res) {
sql.connect("mssql://log:pas#db/TEST").then(function() {
// Query
new sql.Request().query(query).then(function(recordset) {
var a = [];
a.push(recordset[0].Spalte);
res.send(a); // **number**
}).catch(function(err) {
// ... query error checks
});
}).catch(function(err) {
// ... connect error checks
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
Server site in Browser:
My app.js file.
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
//app.get('/');
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
You need only 1 server(REST server). Just use node.js server.
Read it:
REST
I am basically trying to recreate a simple chat application posted on the official website of socket.io.
I created the following module in content.js:
var app = require('express');
var router = app.Router();
module.exports = function(app, io) {
app.get('/profile',function(req, res){
res.render('profile.ejs');
});
io.on('connection', function(socket){
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
return router;
};
I am calling it from index.js through this:
// socket.io
var server = require('http').Server(app);
var io = require('socket.io')(server);
require('./app/content')(app, io);
while running the app, nothing is being sent and the following error(s) are displayed in my console:
GET /socket.io/?EIO=3&transport=polling&t=1461512892706-14 404 2.370 ms - 1097
How can I fix this? as far as i read it got something to do with the location of profile.ejs? Thank you as always for any help
Here is index.js:
var express = require('express')
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var passport = require('passport');
var flash = require('connect-flash');
var session = require('express-session');
var routes = require('./routes/index');
var morgan = require('morgan');
var users = require('./routes/users');
var home = require('./routes/home');
var mysql = require('mysql');
var helmet = require('helmet');
var app = express();
// socket.io
var server = require('http').Server(app);
var io = require('socket.io')(server);
require('./config/passport')(passport); // pass passport for configuration
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'mysql',
database: 'clearreview'
});
connection.connect();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// security measure against xss attacks
app.use(helmet.xssFilter());
// hide powered by express
app.use(helmet.hidePoweredBy());
// security measure against sniffing
app.use(helmet.noSniff());
app.use('/', routes);
// required for passport
app.use(session({
secret: 'vidyapathaisalwaysrunning',
resave: true,
saveUninitialized: true
})); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
// routes ======================================================================
//require('./app/cr-auth-routes.js')(app, passport); // load our routes and pass in our app and fully configured passport
require('./app/cr-auth-routes')(app, passport);
require('./app/search.js')(app, connection);
require('./app/content')(app, io);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
www file that launches the server:
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('clear-review:server');
var http = require('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);
/**
* 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);
}
It appears that you are creating two separate servers, one in your www file with:
var server = http.createServer(app);
And, another one in index.js with:
var server = require('http').Server(app);
You are never starting the one created in index.js and that's the one that socket.io is connected to so that's why you don't have any socket.io functionality. The server you bound socket.io to was never started.
You are starting the one your www file, but it has no socket.io connected to it.
You need to create one server and only one server and have that be the server that Express and socket.io are bound to. And, then you need to start that one server.
I'm using NODE.js and Express (express-generator) to create a website. I had this working just fine yesterday afternoon, but I guess I changed something and it doesn't work now. My firewall is turned off.
I get the following in my console.
C:\website>node bin/www
Listening on 8080
Get / - - ms - -
Get / - - ms - -
Get / - - ms - -
Each of those Get / - - ms - - happens each time I try to go to 127.0.0.1:8080
Here is my bin/www file:
#!/usr/bin/env node
var debug = require('debug')('test');
var app = require('../app');
app.set('port', process.env.PORT || 8080);
var server = app.listen(app.get('port'), function() {
console.log("Listening on " + server.address().port);
debug('Express server listening on port ' + server.address().port);
});
And my app.js:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
// production error handler
app.use(function(err, req, res, next) {
res.status(err.status || 500);
console.log(err);
});
module.exports = app;
This behavior might be the result of incorrectly defined routes. Your routes should follow this pattern:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
module.exports = router;