大家好,首先,我知道这里有很多类似的帖子,但不幸的是我仍然无法弄清楚我的问题。
我有一个文件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');
请问,现在将 app 变量传递到我的 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'));
关于javascript - 将express()应用程序变量从一个文件传递到另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36655241/