首页 > 解决方案 > 我们如何使用 vhost 和 nodejs 添加子域 dynamicllay

问题描述

我想根据用户用户名创建一个子域,因为每个用户的用户名都是唯一的

我手动创建子域,但我不知道如何通过用户名创建它

const subdomain = express();

const domain = "localhost";

  app.use(vhost(`username.${domain}`, subdomain)); //here username is manually i entered

我们如何通过使用 API 从 DB 获取用户名并创建子域来做到这一点

标签: node.jsexpresssubdomainvhosts

解决方案


您可以使用node-awesome-router 这是示例 ho 来配置带有子域的路由,而无需任何 oder(主机、nginx 等)设置

const router = NodeAwesomeRouter({
   app,
     routes: [{
        key: '/path',
        routes: {'/r1': ()=>{}, '/r2': () => {}, ...  },
        subdomain: 'users' // user.domain.com
      }, {
       key: '/path2',
       routes: {'/r1': ()=>{}, '/r2': () => {}, ...  },
       subdomain: 'dev' // dev.domain.com
      }], 
  })

推荐阅读