Express: How to require a file in node js express and pass a parameter value to it?

风流意气都作罢 提交于 2020-01-25 08:42:27

问题


This question has a big relation with How to require a file in node.js and pass an argument in the request method, but not to the module? -- Question.

I have a node js Express app. when visitor visits http://localhost/getPosts, the main node js file requires ./routes/posts file and sends a database connection to the required file.

app.use('/getPosts', require('./routes/posts')(myDatabase));

the content of ./routes/posts file is given below:

var express = require('express');
var router = express.Router();

//Do something with myDatabase here

router.get('/', (req, res, next) => {
    res.render('index');
});
module.exports = router;

My website has multiple pages that is, database connection is required on multiple pages. But it is not possible to make mutiple connection to the same database with the same client(Node JS server). that is why I tried adding the connection code in the main page. how do I get the myDatabase variable on the commented area of the code ?


回答1:


You should export a function that returns the router, like that:

module.exports = dbConnection => {
    var express = require('express');
    var router = express.Router();

    router.get('/', (req, res, next) => {
        res.render('index');
    });

    return router;
};


来源:https://stackoverflow.com/questions/51121533/express-how-to-require-a-file-in-node-js-express-and-pass-a-parameter-value-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!