Node.js + Express.js + Socket.io - javascript

Doesn't work anyway, I really tried so many different ways but nothing works..
I want establish a realtime connection with socket.io to monitor a redis db to get every new added item on a list.
Any ideas ?
app.js
/**
* Module dependencies.
*/
var express = require('express');
var http = require('http');
var path = require('path');
var crawler = require('crawler.js');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
//app.use(express.errorHandler());
}
app.get('/rootaccess',function(req, res){
res.render('crawlercontrol');
});
app.get('/crawler/monitor',function(req, res){
res.render('monitor');
});
app.get('/crawler/start',function(req,res){
crawler.start(res);
});
app.get('/crawler/stop',function(req,res){
crawler.stop(res);
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
var io = require('socket.io').listen(app.listen(3111));
io.sockets.on('connection', function (socket) {
console.log('hei socket.io');
socket.emit('message', { message: 'welcome to the chat' });
socket.on('send', function (data) {
io.sockets.emit('message', data);
});
});
index.html
<!DOCTYPE html>
<html>
<head>
<title>ROOT Monitor</title>
<link rel="stylesheet" href="/css/normalize.css">
<link rel="stylesheet" href="/css/foundation.css" />
<link rel="stylesheet" href="/css/font-awesome.min.css">
<script src="/js/libs/modernizr.js"></script>
</head>
<body>
<div id="monitor">
Monitor
</div>
</body>
<script src="/js/libs/jquery-1.10.2.js"></script>
<script src="/js/libs/foundation.min.js"></script>
<script src='/socket.io/socket.io.js' />
<script>
var socket = io.connect('http://localhost:3111');
socket.on('news', function (data) {
console.log(data);
});
</script>
</script>
</html>
At this moment the only Error which appears is that socket.io doesn't provide the socket.io.js for the client..

I don't know if this is it or not; it's just a hunch. In app.js you tell the express app to listen on the assigned port in the app object:
http.createServer(app).listen(app.get('port'), ...
But then when you create io, you call app.listen() again within the listen method of the object require returns.
var io = require('socket.io').listen(app.listen(3111));
My hunch is that perhaps you are forcing the app server to listen twice which may be causing the issue, again just a hunch. If I am wrong tell me. If you really want to listen on port 3111, you could try this:
var io = require('socket.io').listen(3111);
See if that gets you anywhere.

Related

Trying to serve static JS files Node.js, Err 404

I am trying to set up a simple node.js server to do some basic Socket.io work but when I try to serve my Static JS files I get this error:
GET https://somewebsitewithfiles.website net::ERR_ABORTED 404
Here is my server and local code:
Server:
var express = require('express');
var app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.sendFile(__dirname + '/HTML/index.html');
});
app.use(express.static('Static'))
http.listen(port, () => {
console.log(`Socket.IO server running at http://localhost:${port}/`);
})
Local:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script src="/Static/User.js"></script>
</body>
</html>
As you can see I have used the express static file command witch doesnt seem to be working . My file system consists of my project folder and inside that is my Server JS file. There is also folder in there called "Static" that has has my static files and a folder called HTML that has my index.html
any help appreciated. Thanks
app.use(express.static('Static'))
try putting this line above your '/' route
code:
var express = require('express');
var app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 3000;
app.use(express.static('Static'))
app.get('/', (req, res) => {
res.sendFile(__dirname + '/HTML/index.html');
});
http.listen(port, () => {
console.log(`Socket.IO server running at http://localhost:${port}/`);
})
Edit:
<script src="/Static/User.js"></script>
You dont have to mention the 'static' in the src path.
Correct way:
<script src="/User.js"></script>

Using socket.io and express, why isn't my io.on('connection') method working

I'm trying to teach myself socket.io and node.js by following this tutorial: https://www.youtube.com/watch?v=tzNOqcoupWQ
This is the code that's written by the end of the turotial:
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const path = require('path');
const port = process.env.Port || 3000;
app.use(express.static(path.join(__dirname, 'public')));
app.set('view engine', 'ejs');
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
})
server.listen(port, function(){
console.log('Listening on port ' + port);
io.on('connection', function(socket){
console.log('User Connected! :)');
//handle a new message
socket.on('new:message', function(msgObj){
io.emit('new:message', msgObj);
});
//handle a new member joining
socket.on('new:member', function(name){
io.emit('new:member', name);
});
})
});
The problem is, it seems the io.on('connection' method isn't going through and the "User connected!" message isn't being printed out to the console, yet my index.html loads up just fine (it's just a simple header for now).
What can I do to solve this?
[EDIT]
Here's the index.html
<h1>Hello, World!</h1>
You might need to include the client side socket. i.e add the below code in your html file being served.
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
Integrating Socket.IO in the documentation is a good place to start.

Index.html instead of client stuff on server side

How can I get index.html for my app's client side?
The index page is defined in server.js like this
// load css styles
var css = '<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> ';
css = css + '<style type="text/css">' +require('fs').readFileSync('./style.css').toString() + '</style>'
http.createServer(function (req, res) {
// send basic http headers to client
res.writeHead(200, {
"Content-Type": "text/html",
"Transfer-Encoding": "chunked"
});
// setup simple html page:
res.write("<html>\n<head>\n<title>Newsfeed</title>\n" +css +"</head>\n<body>");
But I want to get an index.html so I can use plain HTML for front-end.
This would explain the long.
Short answer is, you separate view, and use express middlewer for routing.
You must set view location:
app.set('views', __dirname + '/yourViewDirectory');
Put your index.html into /views folder
Then you can use res.render function:
res.render('index.html');
This is the base express server, which render index.html on localhost:3000/
var express = require('express');
var app = express();
app.set('views', __dirname + '/yourViewDirectory');
app.get('/', function (req, res) {
res.render('index.html');
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});

ExpressJS + AngularJS single page without template not found page (404)

My application does not load templates in ng-view inside the index.thml.
I let my code here because i am lost.
app.js
var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
// var $ = require('jquery');
// global.jQuery = $;
// var bootstrap = require('bootstrap');
app.use(express.static(path.join(__dirname, 'public')));
app.set('views', __dirname + 'views');
app.set('view engine', 'html');
var routes = require('./routes');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.get('/', function(req, res) {
res.sendFile(__dirname + "/public/views/index.html");
});
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
console.log('Started Success http://localhost:' + server.address().port);
});
And angular route
angular.module('geradorContrato', ['ngRoute'])
.config(function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/contrato', {
templateUrl: '/public/views/contrato.html',
controller: 'ContratoController'
})
.when('/contratante', {
templateUrl: '/public/views/contratante.html',
controller: 'ContratanteController'
})
.when('/contratada', {
templateUrl: '/public/views/contratada.html',
controller: 'ContratadaController'
})
.when('/bemvindo', {
templateUrl: 'public/views/bemVindo.html',
});
});
But when i access http://localhost:3000/#/bemvindo
The page index.html loading success, but ngview not load and showing the message Cannot GET /public/views/bemVindo.html into console network chrome
Below is my index.html
<!DOCTYPE html>
<html ng-app="geradorContrato">
<head>
<meta charset="UTF-8">
<base href="/">
<link rel='stylesheet' href='/stylesheets/dist/css/bootstrap-theme.css'>
<link rel='stylesheet' href='/stylesheets/dist/css/bootstrap.css'>
<link rel="stylesheet" type="text/css" href="/stylesheets/mainStyle.css">
<script src="/javascript/lib/angular.js"></script>
<script src="/javascript/lib/angular-route.js"></script>
<script src="/javascript/lib/jquery.js"></script>
<script src="/javascript/lib/bootstrap.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular-animate.js"></script>
<script src="/javascript/main.js"></script>
<script src="/javascript/ContratoController.js"></script>
<title>Cadastro</title>
<head>
<body>
<div class="container">
<ng-view></ng-view>
</div>
</body>
</html>
and below is my page simple bemVindo.html
OLÁ SEJA VEM VINDO!
This is base structure my app
Structure
Sorry guys, if you do not understand something tell me pl
sorry for my english
Suggestions
deek:
var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
app.use(express.static(path.join(__dirname, 'public')));
var routes = require('./routes');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use('/', express.static(path.join(__dirname, '/public/views/index.html')));
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
console.log('Started Success http://localhost:' + server.address().port);
});
Error Cannot GET /
path you have given must be wrong, check for the path where your file resides, try to console the path in the javascript console and provide the right path. "Cannot GET /public/views/bemVindo.html" means that the file bemVindo.html is not in the folder /public/views. It is not able to find the file hence showing this error.
Get rid of :
app.set('views', __dirname + 'views');
app.set('view engine', 'html');
Not needed....view engine html is default. Views folder isn't used.
EDIT: remove this too:
app.use(express.static(path.join(__dirname, 'public')));
Change this:
app.get('/', function(req, res) {
res.sendFile(__dirname + "/public/views/index.html");
});
To this:
app.use('/', express.static(path.join(__dirname, '/public/views/index.html')));
Let's express know this is a static directory where the html and supporting files are.
Express will treat it like a normal html directory and try to find an index file. From your index file, the angular will take over routing.
If you wanted to utilize express and templates for routing, the way you did it is best.
You set views folder if you want express to load template files from it but you have none.
You can mix and match with angular too.

Object #<Server> has no method 'use' [Express+ShareJS]

Environment
Express 3.2.4
ShareJS 0.6.2
OS X 10.8.3
Goal
I am trying to get ShareJS running inside of an Express app.
Problem
I get the following error on running node app.js:
/Users/eric/Documents/Projects/collabit/node_modules/share/src/server/index.coffee:52
server.use(options.staticpath, connect["static"]("" + __dirname + "/../.
^
TypeError: Object #<Server> has no method 'use'
at Function.create.attach.attach (/Users/eric/Documents/Projects/collabit/node_modules/share/src/server/index.coffee:52:14)
at Object.<anonymous> (/Users/eric/Documents/Projects/collabit/app.js:43:16)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.runMain (module.js:492:10)
at process.startup.processNextTick.process._tickCallback (node.js:244:9)
I used the express cli interface to generate an app and was working with SocketIO just fine before deciding to swap in ShareJS. I'm pretty sure my issue is how I'm crafting the server but I don't know enough to figure out how I should be creating the server object to keep the express functionality but allow ShareJS to attach.b
Code
/**
* Module dependencies.
*/
var express = require('express')
, sharejs = require('share')
, routes = require('./routes')
, user = require('./routes/user')
, http = require('http')
, path = require('path');
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
app.get('/users', user.list);
var server = http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
/**
* ShareJS Code
*/
var options = {db: {type: 'none'}};
sharejs.server.attach(server, options);
Question
What is the proper way to create my server object in order to allow ShareJS to attach to it while retaining the Express functionality.
Thanks!
Thanks in advance for help and let me know if any additional information is needed.
I had a similar issue. After a lot of trial and error this worked for me:
var express = require('express'),
http = require('http'),
sharejs = require('share').server;
var app = express();
var server = http.createServer(app);
var options = {db:{type:'none'}}; // See docs for options. {type: 'redis'} to enable persistance.
// Attach the sharejs REST and Socket.io interfaces to the server
sharejs.attach(app, options);
app.use(app.router);
app.set('views', __dirname + '/views');
app.engine('html', require('ejs').renderFile);
server.listen(8000, function () {
console.log('Server running at http://127.0.0.1:8000/');
});
app.get('/', function(req, res) {
res.render('share.html');
});
Then in views/share.html I had the standard example html:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="http://ajaxorg.github.com/ace/build/src/ace.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="/channel/bcsocket.js"></script>
<script src="/share/share.js"></script>
<script src="/share/ace.js"></script>
<script>
$(document).ready(function() {
var editor = ace.edit("editor");
sharejs.open('hello', 'text', 'http://localhost:8000/channel', function (error, doc) {
doc.attach_ace(editor);
});
});
</script>
<style>
#editor {
width: 200px;
height: 100px;
}
</style>
</head>
<body>
<div id="editor"></div>
</body>
</html>

Categories

Resources