【问题标题】:subdomain base database connectivity (nodejs + express)子域基础数据库连接(nodejs + express)
【发布时间】:2021-02-02 02:50:28
【问题描述】:

我有一个项目存储库,并为不同的客户提供多个数据库。

以下类型的数据库命名和 URL 连接,我用于根据访问 URL 连接数据库:

客户的数据库

  • shreyas_db (http://shreyas.locahost:3001)
  • ajay_db (http://ajay.locahost:3001)
  • vijay_db (http://vijay.locahost:3001)

请指导如何使用 Express 在 NodeJs 中实现此结构。

谢谢

【问题讨论】:

    标签: node.js express sequelize.js vhosts express-vhost


    【解决方案1】:

    这是我想出的解决方案:

    1. 添加路由器

      app.use('/api', 等待 APIRouter())

    2. 在路由器中间件中连接到不同的 DBS。 获取子域(如果你使用Nginx,你可能会发现req.subdomains 或req.host 没有返回你所期望的,尝试使用req.headers.referer 代替),使用res.locals 保存DB,这样你就可以得到它来自每个 API 调用。

     export const APIRouter = async () => {
          
          const router = express.Router()
          const client = await connectDatabase()
        
          router.use(async (req, res, next) => {
            //const host = req.headers.referer?.replace("https://","");
            //const subdomain = host ? host.substring(0, host.indexOf('.')) : 'main'
            
            const subdomain = req.subdomains.length ? req.subdomains.length[0] : 'main'
            const db = client.db(subdomain)
        
            res.locals.db = {
                clients: db.collection<Client>('clients'),
              }
              next()
            }
          )
         return router
        };

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-17
      • 2017-12-21
      • 1970-01-01
      相关资源
      最近更新 更多