节点快速路由将变量传递给所需的模块

node express routing pass variable to required module

我有一个主 index.js 文件:

var express = require('express')

require("dotenv").config();

const db = require('./services/db_service').db_connection()

const customers = require('./routes/customers');

var app = express();

app.use('/customers', customers)(db) <--- I suppose something like this

app.listen(process.env.PORT, function () {
  console.log(`Example app listening on port ${process.env.PORT}!`)
})

routes/customers.js中:

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

router.get('/' , (req, res) => {
    db.query('SELECT * FROM customers', (err, rows, fields) => { <-- db.query
        if (!err)
            res.send(rows);
        else
            console.log(err);
    })
} );

有没有办法将 dbindex 传递到 routes/customers

您可以编写中间件函数来设置数据库连接:

// index.js
app.use(function (req, res, next) {
  req.db = db
  next()
})

// routes/customers.js
router.get('/' , (req, res) => {
    req.db.query('SELECT * FROM customers', (err, rows, fields) => { <-- db.query
        if (!err)
            res.send(rows);
        else
            console.log(err);
    })
} );