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

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>

Related

Handlebars Templating Engine Not Defined

I am working through Web Development with Node & Express: Leveraging the JavaScript Stack, by Ethan Brown. I am working in chapter three, which introduces basic concepts concerning Express. I created the app, meadowlark.js, as the book has said, and I am getting this error concerning the Handlebars Templating Engine:
ReferenceError: handlebars is not defined
at Object.<anonymous> (/PROJECT_STORAGE/site/meadowlark.js:7:26)
at Module._compile (module.js:410:26)
at Object.Module._extensions..js (module.js:417:10)
at Module.load (module.js:344:32)
at Function.Module._load (module.js:301:12)
at Function.Module.runMain (module.js:442:10)
at startup (node.js:136:18)
at node.js:966:3
Here is the code for how I setup Handlebars and the rest of meadowlark.js:
var express = require('express');
var app = express();
// setup handlebars view engine
var handlbars = require('express-handlebars').create({ defaultLayout: 'main' });
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');
app.set('views', __dirname + '/views');
app.set('port', process.env.PORT || 3000);
app.get('/', function(req, res) {
res.render('home');
});
app.get('/about', function(req, res) {
res.type('about');
});
// custom 404 pg
app.use(function(req, res) {
res.status(404);
res.render('404');
});
// custom 500 pg
app.use(function(err, req, res, next) {
//console.error(err.stack);
res.status(500);
res.render('500');
});
app.listen(app.get('port'), function() {
console.log('Express started on localhost:' + app.get('port') + '; press Ctrl-C to terminate.');
});
How can I fix my code to make Handlebars initialize correctly and make handlebars.js run?
Typo var handlbars = require('express-handlebars').create({ defaultLayout: 'main' });
should be var handlebars.
Pro tip: Use a linter in your ide.

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.

Node.js, express, socket.io app connection error

I've got a simple app which uses socket.io module for node.js.
When i run my server with node express_server.js command it works ok, but when i want to open my http://localhost:8080 page in browser, node throws an error:
/home/tomek/dev/node/node_modules/express/lib/application.js:119
this._router.handle(req, res, function(err) {
^
TypeError: Cannot read property 'handle' of undefined
at Function.app.handle (/home/tomek/dev/node/node_modules/express/lib/application.js:119:15)
at Server.app (/home/tomek/dev/node/node_modules/express/lib/express.js:28:9)
at Manager.handleRequest (/home/tomek/dev/node/node_modules/socket.io/lib/manager.js:565:28)
at Server.<anonymous> (/home/tomek/dev/node/node_modules/socket.io/lib/manager.js:119:10)
at Server.EventEmitter.emit (events.js:110:17)
at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:504:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:111:23)
at Socket.socketOnData (_http_server.js:357:22)
at Socket.EventEmitter.emit (events.js:107:17)
at readableAddChunk (_stream_readable.js:156:16)
My express_server.js file looks like:
var express = require('express'),
socket = require('socket.io'),
http = require ('http');
var app = express();
server = http.createServer(app);
server.listen(8080);
var io = socket.listen(server);
io.sockets.on('connection', function (client) {
console.log('-- Client connected --');
});
and index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Chat application</title>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script>
var server = io.connect('http://localhost:8080');
</script>
</body>
</html>
There is no router defined. Try add this after creating the app (var app = express()):
app.get('/', function(req, res) {
// res.send('hello world');
res.sendfile('index.html');
});
Express is a framework that amongst other stuff replaces the 'http' module. You appear to be trying to use both together. Try this:
var express = require('express'),
var app = express();
app.get('/', function(req, res) {
res.sendfile('index.html');
});
var port = Number(process.env.PORT || 8080);
app.listen(port, function() {
console.log("Listening on " + port);
});
Credit to Ben for the nudge on the get method.

Node.js + Express.js + Socket.io

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.

Strange errors trying to use haml-coffee with an expressJS app

Here is my app.js file following the haml-coffee guides:
// misc requirements
var express = require('express')
, routes = require('./routes')
, http = require('http')
, path = require('path');
// setup app
var app = express();
// set default engine to haml-coffee
app.engine( 'hamlc', require('haml-coffee'.__express ));
// configure misc stuff
app.configure(function(){
app.set('port', process.env.PORT || 3000); // set localhost port to 3000
app.set('views', __dirname + '/views'); // setup views (templates)
app.set('view engine', 'hamlc'); // use haml-coffee as default templating engine
app.set('title', 'Learn Some Code'); // set the website title
app.use(express.favicon()); // favicon handling
app.use(express.logger('dev')); // logging
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router); // use the router
app.use(express.static(path.join(__dirname, 'public')));
});
// only configure this for development
app.configure('development', function(){
app.use(express.errorHandler());
});
app.get('/', routes.index);
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
But when I run node app.js... I get this strange error:
module.js:236
var start = request.substring(0, 2);
^
TypeError: Cannot call method 'substring' of undefined
at Function.Module._resolveLookupPaths (module.js:236:23)
at Function.Module._resolveFilename (module.js:328:31)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:362:17)
at require (module.js:378:17)
at Object.<anonymous> (/Users/chris/src/learnsomecode/app.js:11:22)
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)
Your require has a slight typo in it. Change
app.engine( 'hamlc', require('haml-coffee'.__express ));
to
app.engine( 'hamlc', require('haml-coffee').__express );
'haml-coffee'.__express resolves to undefined, which makes require(undefined) throw the Cannot call method 'substring' of undefined error.

Categories

Resources