To enable the use of a subdomain in Node.js, you can use the module vhost
along with the express
:
npm install vhost
Include it in your code, and put its 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!");
});
Follow 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 through the pages http://admin.localhost:3333 and http://loja.localhost:3333
Welcome to Stack Overflow, Miguel! Please include your code so the community can help you with your problem - and try to explain better what you tried to do, and where it’s going wrong. Enjoy and do the tour to learn more about how the site works!
– Daniel