Express:如何要求节点js中的文件表达并向其传递参数值? [英] Express: How to require a file in node js express and pass a parameter value to it?

查看:158
本文介绍了Express:如何要求节点js中的文件表达并向其传递参数值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题与如何在node.js中要求文件并在request方法中传递参数有关,但是与否无关.到模块? -问题.

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.

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

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));

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

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;

我的网站有多个页面,也就是说,需要在多个页面上建立数据库连接.但是,无法通过相同的客户端(Node JS服务器)建立多个连接到相同的数据库.这就是为什么我尝试在主页中添加连接代码的原因. 如何在代码的注释区域获取myDatabase变量?

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 ?

推荐答案

您应该导出一个返回路由器的函数,如下所示:

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;
};

这篇关于Express:如何要求节点js中的文件表达并向其传递参数值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆