DEV Community

Igor T
Igor T

Posted on

πŸ“’ Express subdomain routing

One day I ran into a problem of how to setup and test express-subdomain lib locally. And after 1 hour of research I resolved my problem :D Here is my solution: Firstly need to add a couple lines to your /etc/hosts file:

127.0.0.1 example.myapp.dev
127.0.0.1 example.dev
And then I created live node js script
//connect express
var express = require('express');
var subdomain = require('express-subdomain');
var app = express();

app.use(express.json());

//set sub routing
app.sub_test = express.Router();
app.use(subdomain('sub_test', app.sub_test));

//top level routing
app.get('/', (req, res) => {
  res.send('Index page')
});

app.get('/index2', (req, res) => {
  res.send('Second index page')
});

//subdomain routing
app.sub_test.get('/', (req, res) => {
  res.send('Subdomain index')
});

app.sub_banana.get('/index2', (req, res) => {
  res.send('Subdomain index2')
});

//start server
var http = require('http');

var port = 3000
app.set('port', port);

var server = http.createServer(app);

server.listen(port);


Express subdomain routing | Exceed Team Blog

Top comments (0)