[英]Pass express() app variable from one file to another
大家好,首先,我知道这里有很多类似的帖子,但不幸的是,我仍然无法弄清我的麻烦。
我有一个文件server.js ,在其中声明我的应用程序变量并调用一些配置内容:
var app = express();
...
在我的其他文件中,该文件位于路径./server/routes/PostApi.js中,我需要这样调用代码:
app.get('/api/posts', function(req, res) {
// use mongoose to get all posts in the database
Post.find(function(err, posts) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err) {
res.send(err);
}
res.json(posts); // return all posts in JSON format
});
...
在此文件的末尾,我致电:
module.exports = PostApi;
首先提到的server.js中需要:
var PostApi = require('./server/routes/PostApi');
拜托,如今将应用变量传递到我的api文件的最佳做法是什么? 谢谢!
因此,直接回答您的问题是,您可以将路线代码转换为接受应用程序作为参数的函数:
module.exports = function(app){
app.get('/api/posts', function(req, res) {
// use mongoose to get all posts in the database
Post.find(function(err, posts) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err) {
res.send(err);
}
res.json(posts); // return all posts in JSON format
});
...
};
也就是说,人们通常会在其路线内构建一个路由器并导出该路由器,然后该应用程序就需要并使用该路由器:
var router = require('express').Router();
router.get(''/api/posts', function(req, res) {
// use mongoose to get all posts in the database
Post.find(function(err, posts) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err) {
res.send(err);
}
res.json(posts); // return all posts in JSON format
});
module.exports = router;
//在app.js中
...
app.use(require('./myrouter.js'));
Paul的答案是正确的,但是无需对文件进行太多更改就可以做到这一点。
module.exports = function(app){
app.get('/api/posts', function(req, res) {
....
});
};
在app.js中
var PostApi = require('./server/routes/PostApi')(app);
这对我有用:
var express = require('express'); // include
var moduleA = require('./moduleA'); // include
var app = express();
var moduleA = new moduleA();
moduleA.execute(app);
app.listen(process.env.PORT || 8080);
function moduleA() {
}
moduleA.prototype.execute = function(app) {
// publish endpoints
app.get('/register',
function(req, res)
{
res.type('text/plain');
res.send('Hello world express!!');
}
);
};
module.exports = moduleA;
并使用以下命令进行测试:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.