10
votes

Using node, express, socket.io, jade and angular. Getting the error: TypeError: Cannot read property 'apply' of undefined. Any suggestions?

index.js:

module.exports = function(app, res) {
  res.render('index', { title: 'Express' });
  var io = app.get('io');
  io.on('connection', function(socket){
  });
};

index.jade:

extends layout

block content

script.
    var app = angular.module('hackigur', []);
    var socket = io.connect();
    var refreshTimer = 10;

    app.controller('UpdateController', function($scope){
        //socket.on('update', function(msg){
            //$scope.refreshTimer = msg;
            //$scope.$apply();
        //});

        setInterval(secondTick,1000);

        function secondTick() {
            if(refreshTimer != 0) {
                refreshTimer -= 1;
            }
            $scope.refreshTimer = refreshTimer;
            $scope.$apply();
        };
    });

h1= title
p Welcome to #{title}

div(ng-controller="UpdateController")
    p(ng-bind="refreshTimer")

layout.jade:

doctype html
html(ng-app="hackigur")
  head
    title= title
    script(src = "/socket.io/socket.io.js")
    script(src = "/js/angular/angular.min.js")
  body
    block content

Full error:

Server listening on port 3000
TypeError: Cannot read property 'apply' of undefined
    at Server.(anonymous function) [as on] (D:\Projects\hackigur\node_modules\so
cket.io\lib\index.js:364:15)
    at module.exports (D:\Projects\hackigur\server\api\index.js:30:8) at ...
1
FYI index.js:30 is the line: io.on('connection', function(socket){ ... this code actually worked last night and I tried again tonight and it died.glog
Could you please post the entirety of index.js? It seems errors are happening on lines you don't include in this question.Scelesto
It just occurred to me that you have multiple index.js's (my bad). Could you at least clarify which index.js you have provided?Scelesto
there's only one index.js... the other is index.jade. i've posted pretty much the entire index.js above; the remainder is just a large function that i've completely commented outglog
index.js I posted is the server/api/index.js; the other socket.io one I didn't touch, it's whatever npm installed in node_modules for socket.ioglog

1 Answers

8
votes

My router which called my index.js passed app in the module.export as such:

module.export = function (app) {
    app.get( ... , function(..., res) { 
        require(index.js)(app)(res);
};

I needed to declare a variable for app external to my module.export:

var x;
module.export = function (app) {
    x = app;
        app.get( ... , function(..., res) { 
        require(index.js)(x)(res);
};

Don't fully understand why it worked, but it seemed to pass the correct app object to app.get by applying the above.