app.set and then TypeError: app.get is not a funct

2019-07-25 12:16发布

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?

4条回答
Root(大扎)
2楼-- · 2019-07-25 12:43

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

查看更多
放我归山
3楼-- · 2019-07-25 12:56

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.

查看更多
Root(大扎)
4楼-- · 2019-07-25 12:59

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.

查看更多
戒情不戒烟
5楼-- · 2019-07-25 13:00

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!

查看更多
登录 后发表回答