【问题标题】:"TypeError: Cannot read property 'apply' of undefined"“TypeError:无法读取未定义的属性‘应用’”
【发布时间】:2016-03-04 21:15:13
【问题描述】:

使用 node、express、socket.io、jade 和 angular。收到错误:TypeError: Cannot read property 'apply' of undefined。有什么建议吗?

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:

文档类型 html html(ng-app="hackigur") 头 标题=标题 脚本(src = "/socket.io/socket.io.js") 脚本(src = "/js/angular/angular.min.js") 身体 阻止内容

完全错误:

服务器监听 3000 端口 TypeError:无法读取未定义的属性“应用” 在 Server.(匿名函数) [as on] (D:\Projects\hackigur\node_modules\so cket.io\lib\index.js:364:15) 在 module.exports (D:\Projects\hackigur\server\api\index.js:30:8) 在 ...

【问题讨论】:

  • 仅供参考 index.js:30 是行:io.on('connection', function(socket){ ...这段代码实际上在昨晚有效,我今晚又试了一次,但它死了。
  • 能否请您发布整个 index.js?似乎错误发生在您未包含在此问题中的行上。
  • 我突然想到你有多个 index.js(我的错)。你能至少澄清一下你提供了哪个 index.js 吗?
  • 只有一个 index.js……另一个是 index.jade。我已经在上面发布了几乎整个 index.js;其余的只是一个我已经完全注释掉的大函数
  • index.js 我贴的是服务器/api/index.js;另一个我没有碰过的socket.io,它是在node_modules中为socket.io安装的任何npm

标签: javascript angularjs node.js express


【解决方案1】:

我的router 调用了我的index.jsmodule.export 中传递了app

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

我需要在我的module.export 外部为app 声明一个变量:

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

不完全理解它为什么起作用,但它似乎通过应用上述方法将正确的app 对象传递给app.get

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多