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?
It looks like app is not being defined. you could also try something like this.
https://stackoverflow.com/a/15018006/1893672
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
and in routes i did something like
in where you have "./routes/path" file:
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.
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:
No require statement should be necessary.
Okay, I have finally figured it out. The
app
was not properly being set within the routes file because we were previously doingmodule.exports = app
afterrequire('./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!