I am trying to send my HTML file as a response form my server.js, but it is not adapting to my HTML changed even after restarting the server.
I have also tried nodemon.
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.get('/', function(req, res, next) {
res.sendFile(__dirname + '/public/index.html');
});
app.use(express.static('public'));
app.set('view cache', true);
io.on('connection', function(client) {
console.log('Client connected...');
client.on('join', function(data) {
console.log(data);
});
client.on('messages', function(data){
client.emit('thread', data);
client.broadcast.emit('thread', data);
});
});
server.listen(7777);
Related
I have two EC2 instances, and I am using socket.io to establish communication between them.
In my First Server I have the following files
server1.js
........
........
var loadData = require("./client/getData");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/', loadData);
var port = Number(process.env.PORT || 5000);
app.listen(port);
var server = require("https").Server(app);
var io = require("socket.io-client");
app.set('socketio', io);
..........
getData.js
......
router.get('/getMetaData', function(req, res){
var io = req.app.get('socketio');
var socket = io.connect('https://172.43.3.2:8080');
socket.on('metaData', function(data){
console.log("MetaData:", data);
res.json(data);
});
});
module.exports = router;
In my Second Server i have the following
server2.js
var express = require('express');
var app = express();
var server = require("https").Server(app);
var io = require("socket.io")(server);
app.get('/', function (req, res) {
res.send('Hello World');
});
var port = Number(process.env.PORT || 5000);
app.listen(port);
var metaData = {
"block1":["id1","id2"]
}
io.on('connection', function(socket){
console.log("Received Connection");
socket.emit('metaData', metaData);
});
console.log("Server Running on:", process.env.PORT);
My request to the route /getMetaData is resulting in "504 Gateway Time-out", I am not sure what I am doing wrong or missing out on
I have the app.js code:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
io.on('connection', function(socket){
socket.on('newRideAdded', function(exclude){
io.emit('newRideAdded', exclude);
});
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.use(express.static(__dirname + '/public/'));
app.use('/rides', require('./routes/rides'));
app.use('/user', require('./routes/user'));
server.listen("8080", function() {
console.log("Connected to db and listening on port 8080");
});
And I want to move the socket io code to its router's page.
That is the router page:
var express = require('express');
var router = express.Router();
var mongojs = require('mongojs');
var db = mongojs("ride4you", []);
router.post('/getRides', function(req, res, next) {
db.rides.find(function(err, docs) {
res.json(docs);
});
});
// rest of the restapi in this page.
// I want socket code to be here
module.exports = router;
As you can see i have each socket emits in each router's page and I already have module.exports in routers page.
How can it be done?
Thanks.
Using Express 4, in your app.js file you can use
app.set('socketio', io);
Then in your router or controller, you can use
router.post('/getRides', function(req, res, next) {
var io = req.app.get('socketio');
io.to(//socket.id//).emit("message", data);
db.rides.find(function(err, docs) {
res.json(docs);
});
};
This is a clean way of passing the reference along.
I run my application is written in Node.js using CMD (Windows OS).
node server.js
There is console.log('Client connected...'); in server file.
But I dont see logs in CMD whene I application is working. How can I fix it?
My code is:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.use(express.static(__dirname + '/bower_components'));
app.get('/', function(req, res,next) {
res.sendFile(__dirname + '/index.html');
});
server.listen(4200);
io.on('connection', function(client) {
console.log('Client connected...');
});
I'm having a problem routing in express 4. I was following the example, but it isn't loading. I'm just getting a spinning wheel.
How do you do routing in express version 4?
app.js:
var express = require('express');
var http = require('http');
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
var port = (process.env.PORT || process.env.VCAP_APP_PORT || 5000);
app.use('/birds', require('./controller/bird'));
http.createServer(function (req, res) {
//res.writeHead(200, {'Content-Type': 'text/plain'});
//res.end('Hello World!\n');
}).listen(port);
console.log('Server running at http://127.0.0.1:'+port);
bird.js:
var express = require('express');
var router = express.Router();
// middleware specific to this router
router.use(function timeLog(req, res, next) {
console.log('Time: ', Date.now());
next();
});
// define the home page route
router.get('/', function(req, res) {
res.send('Birds home page');
});
// define the about route
router.get('/about', function(req, res) {
res.send('About birds');
});
module.exports = router;
You're not calling the app.listen() function. Instead of the http.createServer one, you should invoke the Express function.
Please, take a look at a basic example.
Relevant code:
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
Edit: as slebetman wrote in the comment, the more general way for it is:
http.createServer(app).listen(port, function(){
console.log('now listening on port ' + port);
});
I'm unable to link the index.html page to app.js.I'm trying to send the progress to index.html.But,I'm failing here.How can I overcome this issue?Can anyone please help me out ...
My index.html :
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="bootstrap.js"></script>
<link rel="stylesheet" type="text/css" href="bootstrap.css" />
<div id="progressbar">
</div>
<script>
var socket = io('http://localhost:8085');
socket.on('connect', function(){});
socket.on('message', function(data){
$('#progressbar').progressbar({
maximum: 100,
step: JSON.parse(data).percent
});
});
socket.on('disconnect', function(){});
</script>
My app.js :
var fs = require('fs');
var request = require('request');
var progress = require('request-progress');
var DOWNLOAD_DIR = '/usr/local/';
var file_name = 'googlenew.png'
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express ();
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(8085, function(){
console.log('listening on *:8085');
});
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
console.log("connected :"+socket.id);
});
var callback = function(state){
console.log('received size in bytes', state.received);
console.log('total size in bytes', state.total);
console.log('percent', state.percent);
io.sockets.emit('message', JSON.stringify({size: state.total, received: state.received, percent: state.percent, fileName: file_name}));
}
progress(request('https://www.google.com/images/srpr/logo3w.png'), {
throttle:0,
delay: 0
})
.on('progress', callback)
.pipe(fs.createWriteStream(DOWNLOAD_DIR + file_name))
.on('error', function (err) {
console.log("error");
})
.on('close', function (err){
console.log("Download Complete");
})
Updated 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 fs = require('fs');
var request = require('request');
var progress = require('request-progress');
var DOWNLOAD_DIR = '/usr/local/';
var file_name = 'googlenew.png'
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
var server = app.listen(8085, function(){
console.log('listening on *:8085');
});
var io = require('socket.io')(server);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
console.log("connected :"+socket.id);
});
var callback = function(state){
console.log('received size in bytes', state.received);
console.log('total size in bytes', state.total);
console.log('percent', state.percent);
io.sockets.emit('message', JSON.stringify({size: state.total, received: state.received, percent: state.percent, fileName: file_name}));
}
progress(request('https://www.google.com/images/srpr/logo3w.png'), {
throttle:0,
delay: 0
})
.on('progress', callback)
.pipe(fs.createWriteStream(DOWNLOAD_DIR + file_name))
.on('error', function (err) {
console.log("error");
})
.on('close', function (err){
console.log("Download Complete");
})
// 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(__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;
You are not initializing Express properly so app is not hooked to any web server and thus app.get() isn't active.
Change this:
var app = express ();
var http = require('http').Server(app);
var io = require('socket.io')(http);
http.listen(8085, function(){
console.log('listening on *:8085');
});
to this:
var app = express();
var server = app.listen(8085, function(){
console.log('listening on *:8085');
});
var io = require('socket.io')(server);
See the basic "Hello World" app example in the ExpressJS doc.
And, you will also need to make routes for jquery.js, bootstrap.js, etc... Remember, node.js doesn't serve any files by default. Since they are static files, you will probably want to use app.use(express.static(...)) to serve the static files.