Reputation: 15
In my nodejs application I need to add subdomains dynamically. My application contains a list of books. If a user login to my site and goes to one of the book's details page , the url should change , so that the url should contain the bookname as the subdomain. This should happen for each details page.
Can anyone help me to do this in localhost ?
Versions:
node : v0.10.22
express : 4.12.1
Upvotes: 0
Views: 304
Reputation: 456
There are two problems to consider:
For the first part, configuring your nginx / entry point of your server should be enough and straight forward.
For the second part, you need to be able to determine the given subdomain in a middleware. Express.js actually has something for that, allowing you to write a middleware to handle that:
// ... app creation and other middlewares
app.use(function(req, res, next) {
var requestedSubdomain = req.subdomains.join('.');
// Do something with it, e.g.:
return database.getResourceWithName(requestedSubdomain, function(err, result) {
if (err)
return next(err);
req.resource = result;
// Now all subsequent middleware will have access to the resource via `req.resource`
return next();
});
});
// ... other middlewares and route definitions, then `app.listen()`
Note that, in this specific case, I decided to join the subdomains together to build the resource name, but you may have to adapt it to your situation.
I hope it helps!
Upvotes: 2