Javascript app.set('port', port) 'TypeError: undefined is not a function'。初学者,需要思路
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30184026/
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
app.set('port', port) 'TypeError: undefined is not a function'. Beginner, need ideas
提问by alexcarll
I'm an amateur learning to build with node.js. I've been following a tutorial to create my first node.js app. It worked perfectly until I entered 'npm start'. The log is:
我是一个学习使用 node.js 构建的业余爱好者。我一直在按照教程来创建我的第一个 node.js 应用程序。在我输入“npm start”之前,它运行良好。日志是:
C:\node\nodeteest3\bin\www:16
TypeError: undefined is not a function
at Object.<anonymous> M+<C;\node\nodetest3\bin\www:16:5
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
Then it output about 20 lines starting with "npm ERR! " + filepaths, that I don't think are necessary, as the error seems to be in the bin file. The code for this is
然后它输出大约 20 行以“npm ERR!”+ 文件路径开头,我认为没有必要,因为错误似乎在 bin 文件中。这个代码是
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('nodetest3:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
This is where the error points to:
这是错误指向的地方:
[app.set('port', port);]
-------^error pointer at 's'-so clearly about set------------
-------^ 's' 处的错误指针-关于 set 很清楚------------
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
Like I said in the beginning, I'm a complete beginner with command-line/github, but I'm already in love with it. I try to practice it every night after I finish my homework, and am getting really frustrated about getting stuck because I haven't been able to move forward for four days now. Also, I'm running this on node.js and the OS is Windows 8. Anything helps! Let me know if you want me to post any of the other code; I omitted so as to not add more than necessary.
"../app (app.js file) JUST ADDED"***************************
../app file:
[ App.js ]
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
var app = express();
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json({estended: true}));
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser({extended:true}));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
回答by Deepal
You are not exporting anything in the app.jsfile. At the end of app.jsfile, include following line.
您没有导出app.js文件中的任何内容。在app.js文件末尾,包括以下行。
module.exports = app;
See whether your problem goes away.
看看你的问题是否消失了。
And one more addition: you have var app = express();twice in your app.js.
还有一个补充:你var app = express();的app.js.
回答by fuelusumar
You don't have declared any function called setinside the app.jsfile.
Create that function and export it like this:
您尚未声明set在app.js文件内调用的任何函数。创建该函数并像这样导出它:
exports.set = function(...) { ... };
If this appis the express appyo especify a port like this:
如果这app是快递,请app指定这样的端口:
var express = require('express'),
http = require('http');
var app = express();
http.createServer(app).listen(port);
instead of
代替
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
This is because the port is a property of the http server and not of the express app
这是因为端口是 http 服务器的属性,而不是 express 应用程序的属性
You can use also
你也可以使用
var express = require('express'),
app = express();
app.listen(port);
回答by Petr Odstrcil
Intaned of calling export please use module.export end the end of your script.
在调用导出时,请使用 module.export end 结束您的脚本。
exports = app;module.exports = app;
exports = app;module.exports = app;
回答by Flaudre
At the bottom of your app.js:
在 app.js 的底部:
app.set('port', process.env.PORT || 26398); //<--- replace with your port number
// Server
var server = http.createServer(app);
server.listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
module.exports = app;
回答by Loubot
In my case I simply moved the normalizePort function before the function was called. This was in coffeescript but I've converted it to javascript here.
就我而言,我只是在调用函数之前移动了 normalizePort 函数。这是在coffeescript中,但我已将其转换为javascript here。
normalizePort = function(val) {
var port;
var port;
port = parseInt(val, 10);
if (isNaN(port)) {
return val;
}
if (port >= 0) {
return port;
}
return false;
};
port = normalizePort(process.env.PORT || '4000');
回答by Shubham Jaiswal
Just add "module.exports=app;" in the app.js file.
只需添加“module.exports=app;” 在 app.js 文件中。

