app.set,然后出现TypeError:app.get不是一个函数 [英] app.set and then TypeError: app.get is not a function
问题描述
使用express 4.x时,我将在server.js中设置端口,如下所示.
While using express 4.x, I am setting the port in my server.js like in the following.
var express = require('express');
var app = express();
...
var port = process.env.PORT || 8080;
app.set('port', port);
...
module.exports = app;
但是当我尝试在我的路由文件中访问它时,如下所示...
But when I try to access it within my routes file, like the following...
// path to routes file is app/models, hence the '../../'
var app = require('../../server');
// default route
router.get('/', function (req, res) {
res.send('Hello! The API is at http://localhost:' + app.get('port') + '/api');
});
...出现以下错误.
... I get the following error.
TypeError: app.get is not a function
到底是怎么回事?
推荐答案
好的,我终于明白了.未在路由文件中正确设置 app
,因为我们之前在 require('./app/models/routes'之后执行过
在server.js中.因此,一旦我将应用程序的导出移到了需要routes文件之前,一切就正常了! module.exports = app
);
Okay, I have finally figured it out. The app
was not properly being set within the routes file because we were previously doing module.exports = app
after require('./app/models/routes');
within server.js. So as soon as I moved the exporting of the app to happen before the requiring of the routes file... everything worked!
这篇关于app.set,然后出现TypeError:app.get不是一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!