Javascript “类型错误:无法读取未定义的属性‘应用’”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34012099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:48:45  来源:igfitidea点击:

"TypeError: Cannot read property 'apply' of undefined"

javascriptangularjsnode.jsexpress

提问by glog

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

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

index.js:

索引.js:

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

index.jade:

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:

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 ...

采纳答案by glog

My routerwhich called my index.jspassed appin the module.exportas such:

router该打电话给我index.js传递appmodule.export是这样的:

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

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

我需要app为我的外部声明一个变量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 appobject to app.getby applying the above.

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