【问题标题】:Express: How to require a file in node js express and pass a parameter value to it?Express:如何在 node js express 中要求一个文件并将参数值传递给它?
【发布时间】:2018-12-09 19:37:06
【问题描述】:

这个问题和How to require a file in node.js and pass an argument in the request method, but not to the module? -- Question.有很大关系

我有一个 node js Express 应用程序。当访问者访问http://localhost/getPosts时,主节点js文件需要./routes/posts文件并发送数据库连接到所需文件。

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

./routes/posts 文件的内容如下:

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

//Do something with myDatabase here

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

我的网站有多个页面,即多个页面都需要数据库连接。但是不可能使用同一个客户端(Node JS 服务器)对同一个数据库建立多个连接。这就是我尝试在主页中添加连接代码的原因。 如何在代码的注释区域获取 myDatabase 变量?

【问题讨论】:

    标签: node.js express module require


    【解决方案1】:

    你应该像这样导出一个返回路由器的函数:

    module.exports = dbConnection => {
        var express = require('express');
        var router = express.Router();
    
        router.get('/', (req, res, next) => {
            res.render('index');
        });
    
        return router;
    };
    

    【讨论】:

    • 就是这个!非常感谢您的回答!
    猜你喜欢
    • 1970-01-01
    • 2019-03-09
    • 2019-02-02
    • 1970-01-01
    • 2018-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    相关资源
    最近更新 更多