M
M
Maxim Nine2017-08-10 16:04:32
Node.js
Maxim Nine, 2017-08-10 16:04:32

How to implement subdomain on express Node JS?

I need to implement subdomain on express for node js .
I have not come across this before, please help: either write code sketches, or give the name of npm resources with which I can implement this issue (preferably with git)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2017-08-10
@kulonful

Option 1, different app for each domain:

'use strict';
const http = require('http');
const express = require('express');

const appWWW = express();
const appSub = express();

http.createServer((req, res) => {
  switch(req.headers.host) {
  case 'example.com':
  case 'www.example.com':
    appWWW(req, res);
    break;
  case 'sub.example.com':
    appSub(req, res);
    break;
  }
}).listen(8080);

Option 2, one app, rewrite url using middleware:
'use strict';
const express = require('express');

const app = express();

const WWW_RE = /^www\./i;
app.use((req, res, next) => {
  const host = req.headers.host.replace(WWW_RE, '');
  req.url = '/' + host + req.url;
  next();
});

app.listen(8080);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question