app.set然后TypeError:app.get不是一个函数
当使用快递4.x时,我在我的server.js中设置端口,如下所示。
var express = require('express'); var app = express(); ... var port = process.env.PORT || 8080; app.set('port', port); ... module.exports = app;
但是,当我尝试访问它在我的路线文件,如下所示…
// 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'); });
…我得到以下错误。
TypeError: app.get is not a function
究竟是怎么回事?
好的,我终于明白了。 该app
没有正确设置在路由文件中,因为我们以前在require('./app/models/routes');
之后做module.exports = app
require('./app/models/routes');
在server.js中。 所以只要我移动的应用程序的出口之前要求的路线文件…一切工作!
我不知道到底发生了什么,我不知道你是否会喜欢这个解决scheme。 我曾经有过类似的问题。
在主文件中,我做了类似的事情
var express = require('express'); var app = express(); .... var routes = require("./routes/path") routes(app);
在路线上我做了类似的事情
在你有“./routes/path”文件的地方:
module.exports = function(app){ //I got access to app.locals }
你看我通过快递应用程序。
基本上路线是一个以应用程序作为参数的函数。
我试过app.set(“应用程序”,应用程序),我不认为这工作。
它看起来像应用程序没有被定义。 你也可以尝试这样的事情。
router.get('/', function (req, res) { var app =req.app.get("app") res.send('Hello! The API is at http://localhost:' + app.get("port") + '/api'); });
- Heroku,Node,Express,SSL的ERR_SSL_PROTOCOL_ERROR
- mongodb + express – mongoose不保存“默认”值
- 我是否实现序列化和反序列化NodesJS + Passport + RedisStore?
- 包含和区块在Jade中的区别
- 无法将来自localhost:3000的请求代理到localhost:7000 ReactJs
- 简单的快速应用程序'不能GET /'
- Express.io“无法读取未定义的”expires“属性
- 在node.jsexpression式中,对“/ locations / search”的请求总是进入“/ locations /:location_id”,如何以正确的方式进行路由
- 会话使用护照在node.js中失效