问题
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
What on earth is going on?
回答1:
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!
回答2:
I don't know exactly what's going on and I don't know if you would like this solution. I had a similar problem as this once.
in the main file i did something like
var express = require('express');
var app = express();
....
var routes = require("./routes/path")
routes(app);
and in routes i did something like
in where you have "./routes/path" file:
module.exports = function(app){
//I got access to app.locals
}
you see I passed along the express app .
basically routes is a function that takes app as a parameter.
I tried app.set("app", app) and I don't think that worked.
回答3:
It looks like app is not being defined. you could also try something like this.
router.get('/', function (req, res) {
var app =req.app.get("app")
res.send('Hello! The API is at http://localhost:' + app.get("port") + '/api');
});
https://stackoverflow.com/a/15018006/1893672
回答4:
In your route handling for GET, POST, etc, you should be receiving the 'req' dependency. App should be attached to this so just reference req.app:
router.get('/',function(req,res,next){
console.log(app.get('secret'));
}
No require statement should be necessary.
来源:https://stackoverflow.com/questions/39547614/app-set-and-then-typeerror-app-get-is-not-a-function