我对使用node.js编程相当新,我不太清楚为什么会收到此错误。该函数看起来设置正确,我不相信我有任何异步问题b / c那些应该考虑我自己实现的变量(我认为)。我也尝试过w / o,使用简单的var consolePrint(...)无论如何,这是我下面的代码和下面的错误日志。
/* global __dirname */
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var self = this;
//CALLING HELPER FUNCTION HERE
var server = app.listen(8000, self.consolePrint(server));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use('/public', express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/public/views/index.html');
});
//---------------helper function(s)-------------------//
self.consolePrint = function(serverVar){
var host = serverVar.address().address;
var port = serverVar.address().port;
console.log('Example app listening at http://%s:%s', host, port);
}
和错误:
C:\Users\Daniel\Desktop\workspace\alarm_clock\index.js:17
var server = app.listen(8000, self.consolePrint(server));
^
TypeError: undefined is not a function
at Object.<anonymous> (C:\Users\Daniel\Desktop\workspace\alarm_clock\index.js:17:36)
at Module._compile (module.js:460:26)
at Object.Module._extensions..js (module.js:478:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Function.Module.runMain (module.js:501:10)
at startup (node.js:129:16)
at node.js:814:3
12 May 01:01:36 - [nodemon] app crashed - waiting for file changes before starting...
答案 0 :(得分:4)
这将解决问题:
var server = app.listen(8000, function(){self.consolePrint(server)});
答案 1 :(得分:0)
您在定义之前使用该功能。将监听功能放在&#39; self.consolePrint&#39;赋值语句或在使用之前分配它,它将起作用。