To enable the use of a subdomain in node.js, you can use the vhost
module together with express
:
npm install vhost
Include it in your code, and place your routes before all others:
var vhost = require('vhost');
var admin = express.Router();
app.use(vhost('admin.*', admin));
admin.get('/', function( req, res){
res.send("hello SOpt!");
});
Here is a simple but complete example:
var express = require('express');
var app = express();
app.set('port', process.env.PORT || 3333);
var vhost = require('vhost');
var admin = express.Router();
var loja = express.Router();
app.use(vhost('admin.*', admin));
app.use(vhost('loja.*', loja));
admin.get('/', function( req, res){
res.send("hello admin");
});
loja.get('/', function( req, res){
res.send("hello loja");
});
app.use(function(req, res){
res.type('text/plain');
res.status(404);
res.send('404 - Pagina Nao Encontrada');
});
app.listen(app.get('port'), function(){
console.log('iniciado em http://localhost:' + app.get('port'));
});
Access the link and link